Files for Android and other platforms are removed.
+++ /dev/null
-##
-# This script includes android specific config (GNU GCC)
-##
-import os
-import platform
-import subprocess
-
-Import('env')
-
-SConscript('../external_libs.scons')
-help_vars = Variables()
-if not env.get('ANDROID_NDK'):
- SConscript('../../extlibs/android/ndk/SConscript')
- help_vars.Add(PathVariable('ANDROID_NDK', 'Android NDK root directory', os.path.join(env.get('SRC_DIR'), 'extlibs', 'android', 'ndk', 'android-ndk-r10d')))
-
-if not env.get('ANDROID_GRADLE'):
- SConscript('../../extlibs/android/gradle/SConscript')
- help_vars.Add(PathVariable('ANDROID_GRADLE', 'Android Gradle directory', os.path.join(env.get('SRC_DIR'), 'extlibs', 'android', 'gradle', 'gradle-2.2.1/bin/gradle')))
-
-if not env.get('ANDROID_HOME'):
- SConscript('../../extlibs/android/sdk/SConscript')
-
-
-if env.get('ANDROID_NDK'):
- android_ndk = env.get('ANDROID_NDK')
-else:
- print '''
-*************************************** Info **********************************
-* Android NDK path isn't set, the default will be used. You can set *
-* environment variable ANDROID_NDK or add it in command line as: *
-* # scons ANDROID_NDK=<path to android NDK> ... *
-*******************************************************************************
-'''
- android_ndk = os.path.join(env.get('SRC_DIR'), 'extlibs', 'android', 'ndk', 'android-ndk-r10d')
-
-if env.get('ANDROID_GRADLE'):
- android_gradle = env.get('ANDROID_GRADLE')
-else:
- print '''
-*************************************** Info **********************************
-* Android Gradle path isn't set, the default will be used. You can set *
-* environment variable ANDROID_GRADLE or add it in command line as: *
-* # scons ANDROID_GRADLE=<path to android GRADLE> ... *
-*******************************************************************************
-'''
- android_gradle = os.path.join(env.get('SRC_DIR'), 'extlibs', 'android', 'gradle', 'gradle-2.2.1', 'bin', 'gradle')
-
-help_vars.Update(env)
-Help(help_vars.GenerateHelpText(env))
-src_dir = env.get('SRC_DIR')
-
-# Overwrite suffixes and prefixes
-if env['HOST_OS'] == 'win32':
- env['OBJSUFFIX'] = '.o'
- env['SHOBJSUFFIX'] = '.os'
- env['LIBPREFIX'] = 'lib'
- env['LIBSUFFIX'] = '.a'
- env['SHLIBPREFIX'] = 'lib'
- env['SHLIBSUFFIX'] = '.so'
- env['LIBPREFIXES'] = ['lib']
- env['LIBSUFFIXES'] = ['.a', '.so']
- env['PROGSUFFIX'] = ''
-elif platform.system().lower() == 'darwin':
- env['SHLIBSUFFIX'] = '.so'
- env['LIBSUFFIXES'] = ['.a', '.so']
- env['PROGSUFFIX'] = ''
-
-######################################################################
-# Set common flags
-######################################################################
-
-# Android build system default cofig
-env.AppendUnique(CPPDEFINES = ['ANDROID'])
-env.AppendUnique(CFLAGS = ['-std=c99'])
-env.AppendUnique(SHCFLAGS = ['-Wa,--noexecstack'])
-env.AppendUnique(LINKFLAGS = ['-Wl,--gc-sections', '-Wl,-z,nocopyreloc'])
-
-######################################################################
-# Probe Android NDK default flags
-######################################################################
-ndk_build_cmd = android_ndk + '/ndk-build'
-if env['HOST_OS'] == 'win32':
- if os.path.isfile(ndk_build_cmd + '.cmd'):
- ndk_build_cmd += '.cmd'
-
-if not os.path.isfile(ndk_build_cmd):
- print '''
-*************************************** Error *********************************
-* It seems android ndk path is not set properly, please check if "%s"
-* is the root directory of android ndk. *
-*******************************************************************************
-''' % android_ndk
- Exit(1)
-
-# ANDROID_HOME build option
-if env.get('ANDROID_HOME'):
- android_gradle = env.get('ANDROID_HOME')
-else:
- help_vars = Variables()
- help_vars.Add(PathVariable('ANDROID_HOME', 'ANDROID SDK root directory', os.environ.get('ANDROID_HOME')))
- help_vars.Update(env)
- Help(help_vars.GenerateHelpText(env))
- print '''
-*************************************** Info **********************************
-* Environment variable ANDROID_HOME will use default value. To override *
-* root directory of android sdk, please specify ANDROID_HOME as follows: *
-* scons ANDROID_HOME= <path to Android SDK> *
-*******************************************************************************
-'''
-
-target_arch = env.get('TARGET_ARCH')
-
-# Android ndk early version doesn't support C++11. Detect the toolchain version
-# to make sure proper toolchain is used
-for tc_ver in ['4.7', '4.8', '4.9', '']:
- if os.path.exists(android_ndk + '/toolchains/x86-' + tc_ver):
- break
-
-cmd = [ndk_build_cmd]
-cmd.append('APP_ABI=' + target_arch)
-cmd.append('APP_PLATFORM=android-21')
-cmd.append('APP_STL=gnustl_shared')
-if env.get('RELEASE'):
- cmd.append('APP_OPTIM=release')
-else:
- cmd.append('APP_OPTIM=debug')
-if tc_ver != '':
- cmd.append('NDK_TOOLCHAIN_VERSION=' + tc_ver)
-else:
- print '''
-*************************************** Warning *******************************
-* To support C++11, the toolchain should be >= 4.7, please make sure your *
-* android NDK is at least r8e! *
-*******************************************************************************
-'''
-
-cmd.append('-n')
-
-p = subprocess.Popen(cmd, stdout = subprocess.PIPE)
-
-for flags in p.stdout.readlines():
- if cmp(flags[0:10], 'TC_PREFIX=') == 0: # toolchain prefix (include path)
- prefix = flags[10:].strip()
- env.Replace(CC = prefix + 'gcc')
- env.Replace(CXX = prefix + 'g++')
- env.Replace(AR = prefix + 'ar')
- env.Replace(RANLIB = prefix + 'ranlib')
-
- elif cmp(flags[0:7], 'CFLAGS=') == 0:
- env.AppendUnique(CFLAGS = Split(flags[7:]))
-
- elif cmp(flags[0:9], 'CXXFLAGS=') == 0:
- env.AppendUnique(CXXFLAGS = Split(flags[9:]))
-
- elif cmp(flags[0:8], 'CPPPATH=') == 0:
- env.AppendUnique(CPPPATH = Split(flags[8:]))
-
- elif cmp(flags[0:8], 'SYSROOT=') == 0:
- sysroot = flags[8:].strip()
- env.AppendUnique(LINKFLAGS = ['--sysroot=' + sysroot])
-
- elif cmp(flags[0:8], 'LDFLAGS=') == 0:
- env.AppendUnique(LINKFLAGS = Split(flags[8:]))
-
- elif cmp(flags[0:7], 'TC_VER=') == 0: # set gnustl library path
- ver = flags[7:].strip()
- stl_path = android_ndk + '/sources/cxx-stl/gnu-libstdc++/' + ver + '/libs/' + target_arch
- if target_arch in ['armeabi', 'armeabi-v7a', 'armeabi-v7a-hard']:
- stl_path = stl_path + '/thumb/'
-
- env.AppendUnique(LIBPATH = [stl_path])
- env.Install(env.get('BUILD_DIR'), stl_path + '/libgnustl_shared.so')
-
- elif cmp(flags[0:9], 'PLATFORM=') == 0: # get target platform: android-x
- platform_ver = flags[9+8:].strip()
- if not platform_ver.isdigit():
- platform_ver = ''
-
-
- elif cmp(flags[0:9], 'PLATFORM=') == 0: # get target platform: android-x
- platform_ver = flags[9+8:].strip()
- if not platform_ver.isdigit():
- platform_ver = ''
-
-
- elif cmp(flags[0:9], 'PLATFORM=') == 0: # get target platform: android-x
- platform_ver = flags[9+8:].strip()
- if not platform_ver.isdigit():
- platform_ver = ''
-
-# Determine dependency faux SYS_ROOT
-dep_sys_root = os.path.join(env.get('SRC_DIR'), 'dep', 'android', target_arch, 'usr')
-dep_src_dir = os.path.join(dep_sys_root, 'include')
-dep_lib_dir = os.path.join(dep_sys_root, 'lib')
-
-env['DEP_SYS_ROOT'] = dep_sys_root
-
-# Add external libraries including boost
-env.AppendUnique(CPPPATH = [ dep_src_dir ])
-env.AppendUnique(LIBPATH = [ dep_lib_dir ])
-
-######################################################################
-# Set release/debug flags
-######################################################################
-if env.get('RELEASE'):
- env.AppendUnique(CCFLAGS = ['-Os'])
- env.AppendUnique(CPPDEFINES = ['NDEBUG'])
- env.AppendUnique(LINKFLAGS = ['-s'])
-else:
- env.AppendUnique(CCFLAGS = ['-g'])
-
-if env.get('LOGGING'):
- env.AppendUnique(CPPDEFINES = ['TB_LOG'])
-
-
-env.AppendUnique(CPPDEFINES = ['WITH_POSIX', '__ANDROID__'])
-env.AppendUnique(CCFLAGS = ['-Wall', '-Wextra', '-fPIC'])
-
-env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
-env.AppendUnique(LIBPATH = [src_dir + '/resource/csdk/connectivity/lib/android'])
-env.AppendUnique(LIBS = ['log', 'coap'])
-
-if env.get('SECURED') == '1':
- env.SConscript('#extlibs/mbedtls/SConscript')
- env.AppendUnique(LIBS = ['mbedtls','mbedx509','mbedcrypto'])
-
-# From android-5 (API > 20), all application must be built with flags '-fPIE' '-pie'.
-# Due to the limitation of Scons, it's required to added it into the command line
-# directly (otherwise, it will also be added when build share library)
-env.Replace(CCCOM = '$CC -o $TARGET -c $CFLAGS $CCFLAGS $_CCCOMCOM -fPIE $SOURCES')
-env.Replace(CXXCOM = '$CXX -o $TARGET -c $CXXFLAGS $CCFLAGS $_CCCOMCOM -fPIE $SOURCES')
-env.Replace(LINKCOM = '$LINK -o $TARGET -pie $LINKFLAGS $__RPATH $SOURCES $_LIBDIRFLAGS $_LIBFLAGS')
-
-# Fix android-ndk compatibility issue, make applications build on new NDK can run on old platform
-if platform_ver == '' or int(platform_ver) > 20:
- SConscript('compatibility/c_compat.scons')
-
-SConscript('compatibility/cpp11_compat.scons')
-
-# Make sure that boost for android is available
-SConscript('#extlibs/boost/SConscript')
+++ /dev/null
-#include <sstream>
-#include "android_cpp11_compat.h"
-
-namespace OC {
- template <typename T>
- void from_string(const std::string& s, T& result) {
- std::stringstream ss(s);
- ss >> result; // TODO handle errors
- }
-}
-
-namespace std {
-
- int stoi(const string& s)
- {
- int ret;
- int &ref = ret;
- OC::from_string(s, ref);
- return ret;
- }
-
- double stod(const std::string& s)
- {
- double ret;
- double &ref = ret;
- OC::from_string(s, ref);
- return ret;
- }
-
- long long stoll(const std::string& s)
- {
- long long ret;
- long long int &ref = ret;
- OC::from_string(s, ref);
- return ret;
- }
-
- unsigned long long stoull(const std::string& s)
- {
- unsigned long long ret;
- unsigned long long &ref = ret;
- OC::from_string(s, ref);
- return ret;
- }
-
- long double stold(const string& s)
- {
- long double ret;
- long double &ref = ret;
- OC::from_string(s, ref);
- return ret;
- }
-
- std::string to_string(int t) {
- std::ostringstream os;
- os << t;
- return os.str();
- }
-
- std::string to_string(long t) {
- std::ostringstream os;
- os << t;
- return os.str();
- }
-
- std::string to_string(double t) {
- std::ostringstream os;
- os << t;
- return os.str();
- }
-
- std::string to_string(uint32_t t)
- {
- std::ostringstream os;
- os << t;
- return os.str();
- }
-
-} // std
+++ /dev/null
-#ifndef _ANDRDIO_STRING_H_
-#define _ANDRDIO_STRING_H_
-
-#ifdef __ANDROID__
-#include <string>
-
-#ifndef ANDROID_C11_COMPAT
-using std::to_string;
-#else
-namespace std {
- int stoi(const std::string& s);
- double stod(const std::string& s);
- long long stoll(const std::string& s);
- unsigned long long stoull(const std::string& s);
- long double stold(const string& s);
-
- std::string to_string(int i);
- std::string to_string(long t);
- std::string to_string(uint32_t i);
- std::string to_string(double d);
-}
-#endif
-
-#endif
-
-#endif
\ No newline at end of file
+++ /dev/null
-#include <stdlib.h>
-#include <sys/socket.h>
-
-/* from stdlib.h */
-float strtof(const char *nptr, char **endptr)
-{
- return (float)strtod(nptr, endptr);
-}
-
-double atof(const char *nptr)
-{
- return strtod(nptr, NULL);
-}
-
-int abs(int __n)
-{
- return (__n < 0) ? -__n : __n;
-}
-
-long labs(long __n)
-{
- return (__n < 0L) ? -__n : __n;
-}
-
-long long llabs(long long __n)
-{
- return (__n < 0LL) ? -__n : __n;
-}
-
-int rand(void)
-{
- return (int)lrand48();
-}
-
-void srand(unsigned int __s)
-{
- srand48(__s);
-}
-
-long random(void)
-{
- return lrand48();
-}
-
-void srandom(unsigned int __s)
-{
- srand48(__s);
-}
-
-/* from __cmsg_nxthdr.cpp */
-/*
- * The function __cmsg_nxthd() is missing in Android 4.4, but the Android NDK
- * header files in the version we are using are referencing it and we use it in
- * our code, this functions was added in version 5.0. To make IoTivity
- * dynamically loadable at load time on Android KitKat 4.4 add this functions
- * as a weak symbol, so it will be used if the c lib does not provide it, like
- * on Android < 5.0 This code was taken from these two resources:
- * https://raw.githubusercontent.com/android/platform_bionic/master/libc/bionic/__cmsg_nxthdr.cpp
- * https://github.com/android/platform_bionic/commit/ff64831b0965c16c95c9f81a148f30a6ef3a6c64
- */
-struct cmsghdr* __attribute__((weak)) __cmsg_nxthdr(struct msghdr* msg, struct cmsghdr* cmsg)
-{
- struct cmsghdr* ptr;
- ptr = (struct cmsghdr*)(((unsigned char*) cmsg) + CMSG_ALIGN(cmsg->cmsg_len));
- size_t len = (unsigned long)((char*)(ptr+1) - (char*) msg->msg_control);
- if (len > msg->msg_controllen) {
- return NULL;
- }
- return ptr;
-}
+++ /dev/null
-##
-# This script is for fixing android platform compatibility problem
-##
-
-# To fix android NDK compatibility problem
-# Some functions, e.g. rand, srand. strtof ... are static inline prior to
-# android-L. So before android-L libc.so doesn't include them. If build
-# on android-L and run on an old platform(earlier than android-L), there will
-# be 'can't locate xxx' problem.
-import os
-
-Import('env')
-
-sif_env = env.Clone()
-
-sif_lib = sif_env.StaticLibrary(env.get('BUILD_DIR') + '/c_compat',
- env.SrcToObj(os.path.abspath('./c_compat.c'), env.get('SRC_DIR')))
-
-env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
-env.AppendUnique(LIBS = ['c_compat'])
\ No newline at end of file
+++ /dev/null
-##
-# This script is for fixing android platform compatibility problem
-##
-import os
-
-Import('env')
-
-env.AppendUnique(CPPDEFINES = ['ANDROID_C11_COMPAT'])
-
-cc_env = env.Clone()
-cc_env.AppendUnique(CPPPATH = ['.'])
-cc_lib = cc_env.StaticLibrary(env.get('BUILD_DIR') + '/android_cpp11_compat',
- env.SrcToObj(os.path.abspath('./android_cpp11_compat.cpp'), env.get('SRC_DIR')))
-
-env.AppendUnique(CPPPATH = [os.path.abspath('.')])
-env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
-env.AppendUnique(LIBS = ['android_cpp11_compat'])
+++ /dev/null
-include $(CLEAR_VARS)
-LOCAL_MODULE := flags_probe
-include $(BUILD_SHARED_LIBRARY)
-
-$(info TC_PREFIX=$(TOOLCHAIN_PREFIX))
-$(info CFLAGS=$(TARGET_CFLAGS))
-$(info CXXFLAGS=$(TARGET_CXXFLAGS) $(TARGET_NO_EXECUTE_CFLAGS))
-$(info CPPPATH=$(TARGET_C_INCLUDES) $(__ndk_modules.$(APP_STL).EXPORT_C_INCLUDES))
-$(info SYSROOT=$(SYSROOT_LINK))
-$(info LDFLAGS=$(TARGET_LDFLAGS) $(TARGET_NO_EXECUTE_LDFLAGS) $(TARGET_NO_UNDEFINED_LDFLAGS) $(TARGET_RELRO_LDFLAGS))
-$(info TC_VER=$(TOOLCHAIN_VERSION))
-$(info PLATFORM=$(APP_PLATFORM))
\ No newline at end of file
+++ /dev/null
-##
-# This script includes arduino specific config
-##
-import os
-import platform
-
-Import('env')
-
-def __parse_config(f):
- dict = {}
-
- if not os.path.isfile(f):
- return dict
-
- file = open(f, 'r')
- strs = file.readlines()
- for str in strs:
- str = str.strip()
- if len(str) > 0 and str[0] == '#':
- continue
-
- idx = str.find('=')
- if idx > 0:
- dict.setdefault(str[0:idx], str[idx + 1:])
-
- return dict
-
-def __get_boards(dict):
- boards = []
- keys = dict.keys()
- for key in keys:
- idx = key.find('.name')
- if idx > 0:
- if key.endswith('.name'):
- boards.append(key[0:idx])
- return boards
-
-def __get_cpu(dict, board):
- cpus = []
- keys = dict.keys()
- for key in keys:
- idx = key.find(board + '.menu.cpu.')
- start = len(board + '.menu.cpu.')
- if idx >= 0:
- end = key.find('.', start)
- if end > 0:
- cpu = key[start:end]
- exist = False
- for c in cpus:
- if c == cpu:
- exist = True
- break
-
- if not exist:
- cpus.append(cpu)
- return cpus
-
-def __get_board_info(board, key):
- if cpu:
- v = boards_info.get(board + '.menu.cpu.' + cpu + key)
- if not v:
- v = boards_info.get(board + key)
- else:
- v = boards_info.get(board + key)
- return v
-
-def __search_files(path, pattern, ondisk=True, source=True, strings=False, recursive=True):
- if not recursive:
- return Glob(pattern, ondisk, source, strings)
-
- matches = []
- for root, dirnames, filenames in os.walk(path):
- # This is a helper function to build Arduino libraries. Scripts are using this function
- # to add all the files in a folder as compilation targets rather than specifying each
- # file to compile from a Arduino library folder.
-
- # Since the function is recursive, it adds even "/library/<library-name>/examples" to the
- # compilation list. This is an extra overhead as stack is never going to use ".o" generated
- # for these examples.
- if 'examples' not in root:
- matches.extend(Glob(os.path.join(root, pattern), ondisk, source, strings))
- return matches
-
-# To make sure the src is built in 'BUILD_DIR' (by default it will be built at
-# the same directory as the .c .cpp .S)
-def __src_to_obj(env, srcs):
- objs = []
- prefix = env.get('BOARD') + '_'
- if env.get('CPU'):
- prefix += env.get('CPU') + '_'
-
- build_dir = os.path.join(env.get('BUILD_DIR'), 'arduino')
- for src in srcs:
- if (os.path.isabs(src.path)):
- obj = src.path.replace(arduino_home, build_dir)
- else:
- obj = os.path.join(build_dir, src.path)
- i = obj.rfind('.')
- obj = obj[0:i]
- if env.get('OBJSUFFIX'):
- obj += env.get('OBJSUFFIX')
- objs.extend(env.Object(obj, src, OBJPREFIX=prefix))
- return objs
-
-def __import_lib(env, lib):
- lib_path = os.path.join(arduino_home, 'libraries', lib)
- if not os.path.exists(lib_path):
- if target_arch == 'avr':
- lib_path = os.path.join(arduino_home, 'hardware', 'arduino', 'avr', 'libraries', lib)
- else:
- lib_path = os.path.join(arduino_home, 'hardware', 'arduino', 'sam', 'libraries', lib)
-
- if os.path.exists(os.path.join(lib_path, 'src')):
- lib_path = os.path.join(lib_path, 'src')
-
- env.AppendUnique(CPPPATH = [lib_path])
-
- if os.path.exists(os.path.join(lib_path, 'utility')):
- env.AppendUnique(CPPPATH = [os.path.join(lib_path, 'utility')])
-
- lib_src = []
- lib_src.extend(__search_files(lib_path, '*.S'))
- lib_src.extend(__search_files(lib_path, '*.c'))
- lib_src.extend(__search_files(lib_path, '*.cpp'))
-
- lib_obj = __src_to_obj(env, lib_src)
- build_dir = env.get('BUILD_DIR')
- if build_dir:
- lib_a = env.StaticLibrary(build_dir + lib, lib_obj)
- else:
- lib_a = env.StaticLibrary(lib, lib_obj)
-
- # If we link libSPI.a, the final binary is not getting launched
- # on the board. Which is not the case if we directly use SPI.o.
-
- if env.get('TARGET_ARCH') == 'arm':
- if lib == 'SPI':
- for obj in lib_obj:
- if obj.name.endswith('SPI.o'):
- env.PrependUnique(LIBS = [File(obj)])
- else:
-
- env.AppendUnique(LIBS = [File(lib_a[0])])
- else:
- env.PrependUnique(LIBS = [File(lib_a[0])])
-
- #env.AppendUnique(LIBS = [File(lib_a[0])])
-
-def __build_core(env):
- core_src = __search_files(core_folder, '*.S')
- core_src.extend(__search_files(core_folder, '*.c'))
- core_src.extend(__search_files(core_folder, '*.cpp'))
-
- core_src.extend(__search_files(variant_folder, '*.S'))
- core_src.extend(__search_files(variant_folder, '*.c'))
- core_src.extend(__search_files(variant_folder, '*.cpp'))
-
- core_obj = __src_to_obj(env, core_src)
-
- prefix = env.get('BOARD') + '_'
- if env.get('CPU'):
- prefix += env.get('CPU') + '_'
-
- core = os.path.join(env.get('BUILD_DIR', '.'), 'arduino', prefix + 'core')
- s_core = env.StaticLibrary(core, core_obj)
-
- env.AppendUnique(LIBS = [File(s_core[0])])
-
- # To avoid compiler issue. Otherewise there may be warnings:
- # undefined reference to '_exit' '_close', '_getpid' ...
- # Above functions are used in libc.a and implemented in syscalls_sam3.c
- if env.get('TARGET_ARCH') == 'arm':
- for obj in core_obj:
- if obj.name.endswith('syscalls_sam3.o'):
- env.AppendUnique(LIBS = [File(obj)])
-
-def __create_bin(env, source):
- name = source
- if env.get('TARGET_ARCH') == 'avr':
- eep = env.Command(name + '.eep', source, 'avr-objcopy -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $SOURCE $TARGET')
- hex = env.Command(name + '.hex', source, 'avr-objcopy -O ihex -R .eeprom $SOURCE $TARGET')
- else:
- hex = env.Command(name + '.hex', source, 'arm-none-eabi-objcopy -O binary $SOURCE $TARGET')
-
-#Currently supporting only mega (ie. Arduino ATMega2560) and arduino_due_x/arduino_due_x_dbg (i.e. Arduino Due) builds
-def __upload(env, binary):
- if target_arch == 'avr':
- protocol = __get_board_info(board, '.upload.protocol')
- speed = __get_board_info(board, '.upload.speed')
- port = '/dev/ttyACM0'
- upload_cmd = arduino_home + '/hardware/tools/avr/bin/avrdude -C' + arduino_home +'/hardware/tools/avr/etc/avrdude.conf -p' \
- + mcu + ' -c' + protocol + ' -P' + port + ' -b' + speed + ' -D -Uflash:w:' + binary + ':i'
- print "Upload command: %s" %upload_cmd
- install_cmd = env.Command('install_cmd', None, upload_cmd)
- env.Default('install_cmd')
- elif target_arch == 'arm':
- port = 'ttyACM0'
- upload_cmd = 'stty -F /dev/' + port + ' speed 1200 cs8 -cstopb -parenb \n' + arduino_home + '/hardware/tools/bossac -i --port=' + port + ' -U false -e -w -b ' + binary + ' -R'
- print "Upload command: %s" %upload_cmd
- install_cmd = env.Command('install_cmd', None, upload_cmd)
- env.Default('install_cmd')
-
-# Print the command line that to upload binary to the board
-def __upload_help(env):
- if target_arch == 'avr':
- protocol = __get_board_info(board, '.upload.protocol')
- speed = __get_board_info(board, '.upload.speed')
-
- upload_cmd = arduino_home + '/hardware/tools/avr/bin/avrdude -C' + arduino_home +'/hardware/tools/avr/etc/avrdude.conf -v -v -v -v -p' \
- + mcu + ' -c' + protocol + ' -P<serial_port>' + ' -b' + speed + ' -D -Uflash:w:<hex_file>:i'
- else:
- uu = __get_board_info(board, '.upload.native_usb')
- upload_cmd = arduino_home + '/hardware/tools/bossac -i -d --port=<serial_port> -U ' + uu + ' -e -w -v -b <bin file> -R'
-
- Help('''
-===============================================================================
-You can upload the bin file with following command line:
-''')
- Help('\n $ ' + upload_cmd)
- Help('''
-\nPlease replace <xxx> according to the actual situation.
-===============================================================================
-''')
-
-# ARDUINO_HOME build option
-help_vars = Variables()
-help_vars.Add(PathVariable('ARDUINO_HOME', 'ARDUINO root directory', os.environ.get('ARDUINO_HOME')))
-help_vars.Update(env)
-Help(help_vars.GenerateHelpText(env))
-
-target_arch = env.get('TARGET_ARCH')
-
-# Verify that the arduino, time, red bear, and nordic libraries are
-# installed. If not, get them and install them.
-SConscript(os.path.join(env.get('SRC_DIR'), 'extlibs', 'arduino', 'SConscript'))
-arduino_home = env.get('ARDUINO_HOME')
-print 'ARDUINO_HOME = ' + env.get('ARDUINO_HOME')
-
-# Overwrite suffixes and prefixes
-if env['HOST_OS'] == 'win32':
- env['OBJSUFFIX'] = '.o'
- env['SHOBJSUFFIX'] = '.os'
- env['LIBPREFIX'] = 'lib'
- env['LIBSUFFIX'] = '.a'
- env['SHLIBPREFIX'] = 'lib'
- env['SHLIBSUFFIX'] = '.so'
- env['LIBPREFIXES'] = ['lib']
- env['LIBSUFFIXES'] = ['.a', '.so']
- env['PROGSUFFIX'] = ''
-elif platform.system().lower() == 'darwin':
- env['SHLIBSUFFIX'] = '.so'
- env['LIBSUFFIXES'] = ['.a', '.so']
- env['PROGSUFFIX'] = ''
-
-# Debug/release relative flags
-if env.get('RELEASE'):
- env.AppendUnique(CCFLAGS = ['-Os'])
- env.AppendUnique(CPPDEFINES = ['NDEBUG'])
-else:
- env.AppendUnique(CCFLAGS = ['-g'])
-
-# Force header presence defines
-env.AppendUnique(CPPDEFINES = ['HAVE_ARDUINO_TIME_H'])
-
-# BOARD / CPU option
-
-# Get IDE version
-if os.path.exists(os.path.join(arduino_home, 'lib', 'version.txt')):
- vf = open(os.path.join(arduino_home, 'lib', 'version.txt'), 'r')
- version = vf.readline().replace('.', '').strip()
-else:
- print '''
-************************************* Error ***********************************
-* Can't find version file (lib/version.txt), please check if (%s)
-* is arduino root directory. *
-*******************************************************************************
-''' % arduino_home
- Exit(1)
-
-if version[0:2] == '10':
- is_1_0_x = True
- boards_info = __parse_config(os.path.join(arduino_home, 'hardware', 'arduino', 'boards.txt'))
- env.PrependENVPath('PATH', os.path.join(arduino_home, 'hardware', 'tools', 'avr', 'bin'))
- env.Replace(CC = 'avr-gcc')
- env.Replace(CXX = 'avr-g++')
- env.Replace(AR = 'avr-ar')
- env.Replace(AS = 'avr-as')
- env.Replace(LINK = 'avr-gcc')
- env.Replace(RANLIB = 'avr-ranlib')
- if target_arch != 'avr':
- print '''
-************************************* Error ***********************************
-* Arduino 1.0.x IDE only support 'avr', to support other arch at least 1.5.x *
-* is required.
-*******************************************************************************
-'''
- Exit(1)
-else:
- is_1_0_x = False
- if target_arch == 'avr':
- boards_info = __parse_config(os.path.join(arduino_home, 'hardware', 'arduino', 'avr', 'boards.txt'))
- platform_info = __parse_config(os.path.join(arduino_home, 'hardware', 'arduino', 'avr', 'platform.txt'))
- elif target_arch == 'arm':
- boards_info = __parse_config(os.path.join(arduino_home, 'hardware', 'arduino', 'sam', 'boards.txt'))
- platform_info = __parse_config(os.path.join(arduino_home, 'hardware', 'arduino', 'sam', 'platform.txt'))
- else:
- print '''
-************************************* Error ***********************************
-* CPU arch %s isn't supported currently.
-*******************************************************************************
-''' % target_arch
-
-#Board option, let user to select the board
-boards = __get_boards(boards_info)
-help_vars = Variables()
-help_vars.Add(EnumVariable('BOARD', 'arduino board', boards[0], boards))
-help_vars.Update(env)
-Help(help_vars.GenerateHelpText(env))
-
-#CPU option
-board = env.get('BOARD')
-cpus = __get_cpu(boards_info, board)
-if len(cpus) > 0:
- help_vars = Variables()
- help_vars.Add(EnumVariable('CPU', 'arduino board cpu', cpus[0], cpus))
- help_vars.Update(env)
- Help(help_vars.GenerateHelpText(env))
-
-# Arduino commom flags
-cpu = env.get('CPU')
-board = env.get('BOARD')
-mcu = __get_board_info(board, '.build.mcu')
-f_cpu = __get_board_info(board, '.build.f_cpu')
-usb_vid = __get_board_info(board, '.build.vid')
-usb_pid = __get_board_info(board, '.build.pid')
-variant = __get_board_info(board, '.build.variant')
-
-if not usb_vid:
- usb_vid = __get_board_info(board, '.vid.0')
-if not usb_pid:
- usb_pid = __get_board_info(board, '.pid.0')
-
-if is_1_0_x:
- core_base = os.path.join(arduino_home, 'hardware', 'arduino')
-else:
- if target_arch == 'avr':
- core_base = os.path.join(arduino_home, 'hardware', 'arduino', 'avr')
- else:
- core_base = os.path.join(arduino_home, 'hardware', 'arduino', 'sam')
-
-variant_folder = os.path.join(core_base, 'variants', variant)
-env.AppendUnique(CPPPATH = [variant_folder])
-
-core = __get_board_info(board, '.build.core')
-core_folder = os.path.join(core_base, 'cores', core)
-env.AppendUnique(CPPPATH = [core_folder])
-
-if is_1_0_x:
- comm_flags = ['-std=c99']
- if mcu:
- comm_flags.extend(['-mmcu=' + mcu])
- if f_cpu:
- comm_flags.extend(['-DF_CPU=' + f_cpu])
- comm_flags.extend(['-DARDUINO=' + version])
- if usb_vid:
- comm_flags.extend(['-DUSB_VID=' + usb_vid])
- if usb_pid:
- comm_flags.extend(['-DUSB_PID=' + usb_pid])
-
- env.AppendUnique(ASFLAGS = ['-x', 'assembler-with-cpp'])
- env.AppendUnique(ASFLAGS = comm_flags)
-
- env.AppendUnique(CFLAGS = ['-Os', '-ffunction-sections', '-fdata-sections', '-MMD'])
- env.AppendUnique(CFLAGS = comm_flags)
-
- env.AppendUnique(CXXFLAGS = ['-Os', '-fno-exceptions', '-ffunction-sections', '-fdata-sections','-MMD'])
- env.AppendUnique(CXXFLAGS = comm_flags)
-
- env.AppendUnique(LINKFLAGS = ['-Os'])
- if mcu == 'atmega2560':
- env.AppendUnique(LINKFLAGS = ['-Wl,--gc-sections,--relax'])
- else:
- env.AppendUnique(LINKFLAGS = ['-Wl,--gc-sections'])
- env.AppendUnique(LINKFLAGS = ['-mmcu=' + mcu])
-else:
- if target_arch == 'avr':
- cpu_flag = '-mmcu=' + mcu
- else:
- cpu_flag = '-mcpu=' + mcu
-
- comm_flag = [cpu_flag, '-DF_CPU=' + f_cpu, '-DARDUINO=' + version, '-DARDUINO_' + __get_board_info(board, '.build.board')]
- if target_arch == 'arm':
- # As of 1.5.8 the arduino headers for arm had _asm_ bugs with ARM and
- # require gnu99 to be used
- comm_flag.extend(['-std=gnu99', '-DARDUINO_ARCH_SAM'])
- else:
- comm_flag.extend(['-std=c99', '-DARDUINO_ARCH_AVR'])
-
- compiler_path = platform_info.get('compiler.path')
- compiler_path = compiler_path.replace('{runtime.ide.path}', arduino_home)
- env.PrependENVPath('PATH', compiler_path)
- env.Replace(CC = platform_info.get('compiler.c.cmd'))
- env.Replace(CXX = platform_info.get('compiler.cpp.cmd'))
- env.Replace(AR = platform_info.get('compiler.ar.cmd'))
- if target_arch == 'arm':
- env.AppendUnique(CPPPATH = [os.path.join(arduino_home, 'hardware', 'arduino', 'sam', 'system', 'libsam'),
- os.path.join(arduino_home, 'hardware', 'arduino', 'sam', 'system', 'CMSIS', 'CMSIS', 'Include'),
- os.path.join(arduino_home, 'hardware', 'arduino', 'sam', 'system', '', 'CMSIS', 'Device', 'ATMEL')])
- env.AppendUnique(ASFLAGS = ['-x', 'assembler-with-cpp'])
- env.AppendUnique(ASFLAGS = comm_flag)
- env.AppendUnique(CFLAGS = Split(platform_info.get('compiler.c.flags')))
- env.AppendUnique(CXXFLAGS = Split(platform_info.get('compiler.cpp.flags')))
- env.AppendUnique(ARFLAGS = Split(platform_info.get('compiler.ar.flags')))
- env.AppendUnique(CCFLAGS = comm_flag)
-
- extra_flags = __get_board_info(board, '.build.extra_flags')
- if extra_flags:
- extra_flags = extra_flags.replace('{build.usb_flags}', '')
- env.AppendUnique(CCFLAGS = Split(extra_flags))
- usb_flags = ['-DUSB_VID=' + usb_vid, '-DUSB_PID=' + usb_pid, '-DUSBCON', '-DUSB_MANUFACTURER="Unknown"']
- env.AppendUnique(CCFLAGS = usb_flags)
-
- if target_arch == 'arm':
- env.AppendUnique(LINKFLAGS = ['-Os', '-Wl,--gc-sections', cpu_flag,
- '-T' + os.path.join(variant_folder, __get_board_info(board, '.build.ldscript'))])
- env.AppendUnique(LINKFLAGS = Split('-lm -lgcc -mthumb -Wl,--check-sections -Wl,--gc-sections -Wl,--entry=Reset_Handler -Wl,--unresolved-symbols=report-all -Wl,--warn-common -Wl,--warn-section-align -Wl,--warn-unresolved-symbols -Wl,--start-group'))
-
- variant_system_lib = __get_board_info(board, '.build.variant_system_lib')
- if variant_system_lib:
- if variant_folder.find(' ') >= 0:
- variant_folder = '"' + variant_folder + '"'
- env.Replace(LINKCOM = '$LINK -o $TARGET $_LIBDIRFLAGS $LINKFLAGS $SOURCES $_LIBFLAGS '
- + os.path.join(variant_folder, variant_system_lib) + ' -Wl,--end-group')
- else:
- env.Replace(LINKCOM = '$LINK -o $TARGET $_LIBDIRFLAGS $LINKFLAGS $SOURCES $_LIBFLAGS -Wl,--end-group')
- else:
- env.AppendUnique(LINKFLAGS = Split(platform_info.get('compiler.c.elf.flags')))
- env.AppendUnique(LINKFLAGS = [cpu_flag])
- env.AppendUnique(LIBS = 'm')
- env.Replace(ARCOM = '$AR ' + platform_info.get('compiler.ar.flags') + ' $TARGET $SOURCES')
-
-# Make sure the .d files are removed when clean the build
-if env.GetOption('clean'):
- dfs = __search_files(env.get('BUILD_DIR'), '*.d')
- for df in dfs:
- Execute(Delete(df))
-__build_core(env)
-
-env.AddMethod(__import_lib, "ImportLib") #import arduino library
-env.AddMethod(__build_core, "BuildCore") #build arduino core
-env.AddMethod(__create_bin, "CreateBin") #create binary files(.eep and .hex)
-env.AddMethod(__upload, "Upload") #Upload binary to board
-env.AddMethod(__upload_help, "UploadHelp") #print the command line that to upload binary to the boardf
+++ /dev/null
-##
-# This script set ios specific flags (GNU GCC)
-#
-##
-Import('env')
-
-# setting of IOS is almost the same as Darwin(MAC OSX)
-env.SConscript('../darwin/SConscript')
-
-sys_version = env.get('SYS_VERSION')
-if env.get('TARGET_ARCH') in ['i386', 'x86_64']: #Simulator
- flag = '-mios-simulator-version-min=' + sys_version
- env.AppendUnique(CCFLAGS = [flag])
- env.AppendUnique(LINKFLAGS = [flag])
-else:
- flag = '-miphoneos-version-min=' + sys_version
- env.AppendUnique(CCFLAGS = [flag])
- env.AppendUnique(LINKFLAGS = [flag])
\ No newline at end of file
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2014 MediaTek 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 <sstream>
-#include "OCAndroid.h"
-
-namespace OC {
- template <typename T>
- void from_string(const std::string& s, T& result) {
- std::stringstream ss(s);
- ss >> result; // TODO handle errors
- }
-
- /*
- template <typename T>
- std::string to_string(T value)
- {
- std::ostringstream os ;
- os << value ;
- return os.str() ;
- }
- */
-
-}
-
-namespace std {
-
- int stoi(const string& s)
- {
- int ret;
- int &ref = ret;
- OC::from_string(s, ref);
- return ret;
- }
-
- double stod(const std::string& s)
- {
- double ret;
- double &ref = ret;
- OC::from_string(s, ref);
- return ret;
- }
-
- long long stoll(const std::string& s)
- {
- long long ret;
- long long int &ref = ret;
- OC::from_string(s, ref);
- return ret;
- }
-
- unsigned long long stoull(const std::string& s)
- {
- unsigned long long ret;
- unsigned long long &ref = ret;
- OC::from_string(s, ref);
- return ret;
- }
-
- long double stold(const string& s)
- {
- long double ret;
- long double &ref = ret;
- OC::from_string(s, ref);
- return ret;
- }
-
- #define TO_STRING(_t) { \
- std::ostringstream os; \
- os << _t; \
- return os.str(); \
- } \
-
- std::string to_string(int val)
- {
- TO_STRING(val)
- }
-
- std::string to_string(long val)
- {
- TO_STRING(val)
- }
-
- std::string to_string(long long val)
- {
- TO_STRING(val)
- }
-
- std::string to_string(unsigned val)
- {
- TO_STRING(val)
- }
-
- std::string to_string(unsigned long val)
- {
- TO_STRING(val)
- }
-
- std::string to_string(unsigned long long val)
- {
- TO_STRING(val)
- }
-
- std::string to_string(float val)
- {
- TO_STRING(val)
- }
-
- std::string to_string(double val)
- {
- TO_STRING(val)
- }
-
- std::string to_string(long double val)
- {
- TO_STRING(val)
- }
-} // std
+++ /dev/null
-##
-# Android Compatibility (static library) build script
-##
-Import('env')
-
-compatibilitylib_env = env.Clone()
-######################################################################
-# Build flags
-######################################################################
-compatibilitylib_env.AppendUnique(CPPPATH = ['../include/'])
-
-target_os = env.get('TARGET_OS')
-
-if target_os == 'android':
- compatibilitylib_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
- compatibilitylib_env.AppendUnique(LIBS = ['gnustl_shared'])
-
-######################################################################
-# Source files and Targets
-######################################################################
-compatibilitylib_src = ['OCAndroid.cpp']
-
-if target_os == 'android':
- static_compatibilitylib = compatibilitylib_env.StaticLibrary('compatibility', compatibilitylib_src)
- compatibilitylib_env.InstallTarget(static_compatibilitylib, 'libcompatibility')
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<module external.linked.project.id="EasySetupCore" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$" external.system.id="GRADLE" external.system.module.group="" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
- <component name="FacetManager">
- <facet type="android-gradle" name="Android-Gradle">
- <configuration>
- <option name="GRADLE_PROJECT_PATH" value=":" />
- </configuration>
- </facet>
- <facet type="android" name="Android">
- <configuration>
- <option name="SELECTED_BUILD_VARIANT" value="debug" />
- <option name="SELECTED_TEST_ARTIFACT" value="_android_test_" />
- <option name="ASSEMBLE_TASK_NAME" value="assembleDebug" />
- <option name="COMPILE_JAVA_TASK_NAME" value="compileDebugSources" />
- <afterSyncTasks>
- <task>generateDebugSources</task>
- </afterSyncTasks>
- <option name="ALLOW_USER_CONFIGURATION" value="false" />
- <option name="MANIFEST_FILE_RELATIVE_PATH" value="/src/main/AndroidManifest.xml" />
- <option name="RES_FOLDER_RELATIVE_PATH" value="/src/main/res" />
- <option name="RES_FOLDERS_RELATIVE_PATH" value="file://$MODULE_DIR$/src/main/res" />
- <option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" />
- <option name="LIBRARY_PROJECT" value="true" />
- </configuration>
- </facet>
- </component>
- <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_7" inherit-compiler-output="false">
- <output url="file://$MODULE_DIR$/build/intermediates/classes/debug" />
- <output-test url="file://$MODULE_DIR$/build/intermediates/classes/test/debug" />
- <exclude-output />
- <content url="file://$MODULE_DIR$">
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/debug" isTestSource="false" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/debug" isTestSource="false" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/debug" isTestSource="false" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/debug" isTestSource="false" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/debug" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/debug" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/androidTest/debug" isTestSource="true" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/androidTest/debug" isTestSource="true" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/androidTest/debug" isTestSource="true" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/androidTest/debug" isTestSource="true" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/androidTest/debug" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/androidTest/debug" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/res" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/resources" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/assets" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/aidl" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/java" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/jni" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/rs" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/testDebug/res" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/testDebug/resources" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/testDebug/assets" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/testDebug/aidl" isTestSource="true" />
- <sourceFolder url="file://$MODULE_DIR$/src/testDebug/java" isTestSource="true" />
- <sourceFolder url="file://$MODULE_DIR$/src/testDebug/jni" isTestSource="true" />
- <sourceFolder url="file://$MODULE_DIR$/src/testDebug/rs" isTestSource="true" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/res" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/assets" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/aidl" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/java/common" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/java/interface" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/jni" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/rs" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/res" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/resources" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/assets" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/aidl" isTestSource="true" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/java" isTestSource="true" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/jni" isTestSource="true" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/rs" isTestSource="true" />
- <sourceFolder url="file://$MODULE_DIR$/src/test/res" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/test/resources" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/test/assets" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/test/aidl" isTestSource="true" />
- <sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" />
- <sourceFolder url="file://$MODULE_DIR$/src/test/jni" isTestSource="true" />
- <sourceFolder url="file://$MODULE_DIR$/src/test/rs" isTestSource="true" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/assets" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/bundles" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/classes" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dependency-cache" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/exploded-aar/EasySetupCore/iotivity-base-armeabi-debug/unspecified/jars" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/lint" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/manifests" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/mockable-android-21.jar" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/res" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/resources" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/rs" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/symbols" />
- <excludeFolder url="file://$MODULE_DIR$/build/outputs" />
- <excludeFolder url="file://$MODULE_DIR$/build/tmp" />
- </content>
- <orderEntry type="jdk" jdkName="Android API 21 Platform" jdkType="Android SDK" />
- <orderEntry type="sourceFolder" forTests="false" />
- <orderEntry type="library" exported="" scope="TEST" name="mockable-android-21" level="project" />
- <orderEntry type="module" module-name="iotivity-base-armeabi-debug" exported="" />
- <orderEntry type="library" exported="" name="iotivity-base-armeabi-debug-unspecified" level="project" />
- </component>
-</module>
\ No newline at end of file
+++ /dev/null
-apply plugin: 'com.android.library'
-// Top-level build file where you can add configuration options common to all sub-projects/modules.
-
-android {
- compileSdkVersion 21
- buildToolsVersion '20.0.0'
- archivesBaseName = "iotivity"
-
- libraryVariants.all { variant ->
- variant.outputs.each { output ->
- def outputFile = output.outputFile
- if (outputFile != null && outputFile.name.endsWith('.aar')) {
- def fileName = "${outputFile.name}"
- output.outputFile = new File(outputFile.parent, fileName)
- }
- }
- }
-
- defaultConfig {
- minSdkVersion 21
- targetSdkVersion 21
- versionCode 1
- versionName "1.0"
- }
-
- repositories {
- flatDir {
- dirs '../../../../../../android/android_api/base/build/outputs/aar'
- }
- }
-
- buildTypes {
- release {
- minifyEnabled false
- proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
- }
- }
-
- lintOptions {
- abortOnError false
- }
- sourceSets {
- main {
- manifest.srcFile 'src/main/AndroidManifest.xml'
- jni.srcDirs = [] //disable automatic ndk-build call
- jniLibs.srcDir new File(buildDir, 'native-libs')
- }
- //androidTest.setRoot('src/androidTest')
- }
-}
-
-dependencies {
- compile ":iotivity-base-${TARGET_ARCH}-${RELEASE}@aar"
- androidTestCompile 'com.google.dexmaker:dexmaker-mockito:1.0'
- androidTestCompile 'com.google.dexmaker:dexmaker:1.0'
- androidTestCompile 'org.mockito:mockito-core:1.10.19'
-}
-
-////////////////
-////NDK Support
-////////////////
-//If using this, Android studio will fail run the following to set the environment variable for android studio:
-//launchctl setenv ANDROID_NDK_HOME
-//otherwise remove the dependsOn part and run ./gradlew buildNative from the command line
-task copyNativeLibs(type: Copy, dependsOn: 'buildNative') {
- dependsOn 'buildNative'
- from(new File('src/main/libs/armeabi')) { include '**/*.so' exclude '**/libgnustl_shared.so', '**/liboc.so', '**/libocstack-jni.so'}
- into new File(buildDir, 'native-libs/armeabi')
-}
-
-tasks.withType(JavaCompile) { compileTask -> compileTask.dependsOn copyNativeLibs }
-
-clean.dependsOn 'cleanCopyNativeLibs'
-
-tasks.withType(com.android.build.gradle.tasks.PackageApplication) {
- pkgTask ->
- pkgTask.jniFolders = new HashSet<File>()
- pkgTask.jniFolders.add(new File(buildDir, 'native-libs'))
-}
-
-task buildNative(type: Exec) {
- if (System.env.ANDROID_NDK_HOME != null) {
- //for windows use 'ndk-build.cmd'
- //def ndkBuild = new File(System.env.ANDROID_NDK_HOME, 'ndk-build.cmd')
- def ndkBuild = new File(System.env.ANDROID_NDK_HOME, 'ndk-build')
- commandLine ndkBuild, "APP_ABI=$TARGET_ARCH", "APP_OPTIM=$RELEASE", '-C', file('src/main').absolutePath
- } else {
- println '##################'
- println 'Skipping NDK build'
- println 'Reason: ANDROID_NDK_HOME not set.'
- println '##################'
- }
-}
\ No newline at end of file
+++ /dev/null
-# Add project specific ProGuard rules here.
-# By default, the flags in this file are appended to flags specified
-# in C:/android/sdk/tools/proguard/proguard-android.txt
-# You can edit the include path and order by changing the proguardFiles
-# directive in build.gradle.
-#
-# For more details, see
-# http://developer.android.com/guide/developing/tools/proguard.html
-
-# Add any project specific keep options here:
-
-# If your project uses WebView with JS, uncomment the following
-# and specify the fully qualified class name to the JavaScript interface
-# class:
-#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
-# public *;
-#}
+++ /dev/null
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="org.iotivity.service.easysetup.mediator"
- android:versionCode="1"
- android:versionName="1.0" >
-
- <uses-sdk
- android:minSdkVersion="8"
- android:targetSdkVersion="21" />
-
- <application
- android:allowBackup="true"
- android:icon="@drawable/ic_launcher"
- android:label="@string/app_name"
- android:theme="@style/AppTheme" >
- </application>
-
-</manifest>
+++ /dev/null
-/**
- * ***************************************************************
- *
- * Copyright 2016 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.iotivity.service.easysetup.mediator;
-
-import android.util.Log;
-
-import org.iotivity.service.easysetup.mediator.enums.OAUTH_TOKENTYPE;
-
-import org.iotivity.base.OcException;
-import org.iotivity.base.OcRepresentation;
-
-/**
- * This class contains cloud server properties to be delivered to Enrollee
- */
-public class CloudProp {
- private static final String TAG = CloudProp.class.getName();
- protected OcRepresentation mRep = null;
- protected String mCloudID = null;
- protected int mCredID ;
-
- /**
- * Constructor
- */
- public CloudProp() {
- mRep = new OcRepresentation();
- mCloudID = "";
- }
-
- public void setCloudProp(String authCode, String authProvider, String ciServer)
- {
- if(authCode == null)
- {
- authCode = "";
- }
- if(authProvider == null)
- {
- authProvider = "";
- }
- if(ciServer == null)
- {
- ciServer = "";
- }
- try {
- mRep.setValue(ESConstants.OC_RSRVD_ES_AUTHCODE, authCode);
- mRep.setValue(ESConstants.OC_RSRVD_ES_AUTHPROVIDER, authProvider);
- mRep.setValue(ESConstants.OC_RSRVD_ES_CISERVER, ciServer);
- } catch (OcException e) {
- Log.e(TAG, "setCloudProp is failed.");
- }
- }
-
- public void setCloudPropWithAccessToken(String accessToken, OAUTH_TOKENTYPE tokenType,
- String authProvider, String ciServer)
- {
- if(accessToken == null)
- {
- accessToken = "";
- }
- if(authProvider == null)
- {
- authProvider = "";
- }
- if(ciServer == null)
- {
- ciServer = "";
- }
- try {
- mRep.setValue(ESConstants.OC_RSRVD_ES_ACCESSTOKEN, accessToken);
- mRep.setValue(ESConstants.OC_RSRVD_ES_ACCESSTOKEN_TYPE, tokenType.getValue());
- mRep.setValue(ESConstants.OC_RSRVD_ES_AUTHPROVIDER, authProvider);
- mRep.setValue(ESConstants.OC_RSRVD_ES_CISERVER, ciServer);
- } catch (OcException e) {
- Log.e(TAG, "setCloudPropWithAccessToken is failed.");
- }
- }
-
- public void setCloudID(String cloudID)
- {
- mCloudID = cloudID;
- }
-
- public void setCredID(int credID)
- {
- mCredID = credID;
- }
- /**
- * This method returns the authCode used for the first registration to IoTivity cloud
- * @return AuthCode for sign-up to IoTivity cloud
- */
- public String getAuthCode()
- {
- if(mRep == null)
- {
- return null;
- }
-
- try
- {
- if (mRep.hasAttribute(ESConstants.OC_RSRVD_ES_AUTHCODE))
- return mRep.getValue(ESConstants.OC_RSRVD_ES_AUTHCODE);
- }
- catch (OcException e)
- {
- Log.e(TAG, "getAuthCode is failed.");
- }
- return null;
- }
-
- /**
- * This method returns the auth provider which issued the given AuthCode
- * @return Auth provider which issued the given AuthCode
- */
- public String getAuthProvider()
- {
- if(mRep == null)
- {
- return null;
- }
-
- try
- {
- if (mRep.hasAttribute(ESConstants.OC_RSRVD_ES_AUTHPROVIDER))
- return mRep.getValue(ESConstants.OC_RSRVD_ES_AUTHPROVIDER);
- }
- catch (OcException e)
- {
- Log.e(TAG, "getAuthProvider is failed.");
- }
- return null;
- }
-
- /**
- * This method returns the Cloud Interface server's URL to be registered
- * @return CI server's URL to be registered
- */
- public String getCiServer()
- {
- if(mRep == null)
- {
- return null;
- }
-
- try
- {
- if (mRep.hasAttribute(ESConstants.OC_RSRVD_ES_CISERVER))
- return mRep.getValue(ESConstants.OC_RSRVD_ES_CISERVER);
- }
- catch (OcException e)
- {
- Log.e(TAG, "getCiServer is failed.");
- }
- return null;
- }
-
- /**
- * This method returns the Cloud Interface server's UUID
- * @return CI server's UUID
- */
- public String getCloudID()
- {
- return mCloudID;
- }
-
- /**
- * This method returns the Cloud Certificate's Cred ID
- * @return CI server's Credential ID of Certificate
- */
- public int getCredID()
- {
- return mCredID;
- }
-
- /**
- * This method returns an accessToken used for the first registration to IoTivity cloud
- * @return accessToken for sign-up to IoTivity cloud
- */
- public String getAccessToken()
- {
- if(mRep == null)
- {
- return null;
- }
-
- try
- {
- if (mRep.hasAttribute(ESConstants.OC_RSRVD_ES_ACCESSTOKEN))
- return mRep.getValue(ESConstants.OC_RSRVD_ES_ACCESSTOKEN);
- }
- catch (OcException e)
- {
- Log.e(TAG, "getAccessToken is failed.");
- }
- return null;
- }
-
- /**
- * This method returns an access token type
- * @return tokenType of access token
- */
- public OAUTH_TOKENTYPE getAccessTokenType()
- {
- if(mRep == null)
- {
- return null;
- }
-
- try
- {
- if (mRep.hasAttribute(ESConstants.OC_RSRVD_ES_ACCESSTOKEN_TYPE))
- return OAUTH_TOKENTYPE.fromInt((int)mRep.getValue(ESConstants.OC_RSRVD_ES_ACCESSTOKEN_TYPE));
- }
- catch (OcException e)
- {
- Log.e(TAG, "getAccessTokenType is failed.");
- }
- return OAUTH_TOKENTYPE.NONE_OAUTH_TOKENTYPE;
- }
-
- public OcRepresentation toOCRepresentation()
- {
- return mRep;
- }
-}
+++ /dev/null
-/**
- * ***************************************************************
- *
- * Copyright 2016 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.iotivity.service.easysetup.mediator;
-
-import org.iotivity.service.easysetup.mediator.CloudPropProvisioningStatus;
-
-/**
- * This interface class is used as a callback function called after receiving
- * a response of cloud property provisioning result
- *
- * @see CloudPropProvisioningStatus
- */
-public abstract class CloudPropProvisioningCallback {
-
- /**
- * Called after receiving a response of cloud property provisioning result
- *
- * @param status
- * a result of cloud property provisioning
- * a state of cloud property provisioning
- */
- public abstract void onProgress(CloudPropProvisioningStatus status);
-}
-
+++ /dev/null
-/**
- * ***************************************************************
- *
- * Copyright 2016 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.iotivity.service.easysetup.mediator;
-
-import org.iotivity.service.easysetup.mediator.enums.ESCloudProvState;
-import org.iotivity.service.easysetup.mediator.enums.ESResult;
-
-/**
- * This interface facilitates Application to get progress & result of Cloud provisioning
- * process in easy setup
- */
-public class CloudPropProvisioningStatus
-{
- private ESResult m_result;
-
- /**
- * Constructor
- *
- * @param result a result of cloud property provisioning
- * @param state a state of cloud property provisioning.
- * ES_CLOUD_PROVISIONING_ERROR(-1), ES_CLOUD_PROVISIONING_SUCCESS(0),
- * ES_CLOUD_ENROLLEE_FOUND(1), ES_CLOUD_ENROLLEE_NOT_FOUND(2)
- *
- * @see ESCloudProvState
- */
- public CloudPropProvisioningStatus(int result)
- {
- m_result = ESResult.fromInt(result);
- }
-
- /**
- * Get a result of cloud property provisioning
- *
- * @result ESResult a result of cloud property provisioning
- */
- public ESResult getESResult()
- {
- return m_result;
- }
-};
+++ /dev/null
-/**
- * ***************************************************************
- *
- * Copyright 2016 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.iotivity.service.easysetup.mediator;
-
-import android.util.Log;
-
-import org.iotivity.service.easysetup.mediator.enums.WIFI_AUTHTYPE;
-import org.iotivity.service.easysetup.mediator.enums.WIFI_ENCTYPE;
-
-import org.iotivity.base.OcException;
-import org.iotivity.base.OcRepresentation;
-
-/**
- * This class contains device properties to be delivered to Enrollee
- */
-public class DeviceProp {
- private static final String TAG = DeviceProp.class.getName();
- protected OcRepresentation mRep = null;
-
- /**
- * Constructor
- */
- public DeviceProp() {
- mRep = new OcRepresentation();
- }
-
- public void setWiFiProp(String ssid, String pwd, WIFI_AUTHTYPE authtype, WIFI_ENCTYPE enctype)
- {
- if(ssid == null)
- {
- ssid = "";
- }
- if(pwd == null)
- {
- pwd = "";
- }
- try
- {
- mRep.setValue(ESConstants.OC_RSRVD_ES_SSID, ssid);
- mRep.setValue(ESConstants.OC_RSRVD_ES_CRED, pwd);
- mRep.setValue(ESConstants.OC_RSRVD_ES_AUTHTYPE, authtype.getValue());
- mRep.setValue(ESConstants.OC_RSRVD_ES_ENCTYPE, enctype.getValue());
- } catch (OcException e) {
- Log.e(TAG, "setWiFiProp is failed.");
- }
- }
-
- public void setDevConfProp(String language, String country, String location)
- {
- if(language == null)
- {
- language = "";
- }
- if(country == null)
- {
- country = "";
- }
- if(location == null)
- {
- location = "";
- }
- try {
- mRep.setValue(ESConstants.OC_RSRVD_ES_LANGUAGE, language);
- mRep.setValue(ESConstants.OC_RSRVD_ES_COUNTRY, country);
- mRep.setValue(ESConstants.OC_RSRVD_ES_LOCATION, location);
- } catch (OcException e) {
- Log.e(TAG, "setDevConfProp is failed.");
- }
- }
-
- /**
- * Get WiFi AP's SSID
- *
- * @return String WiFi AP's SSID
- */
- public String getSsid()
- {
- if(mRep == null)
- {
- return null;
- }
-
- try
- {
- if(mRep.hasAttribute(ESConstants.OC_RSRVD_ES_SSID))
- return mRep.getValue(ESConstants.OC_RSRVD_ES_SSID);
- }
- catch (OcException e)
- {
- Log.e(TAG, "getSsid is failed.");
- }
- return null;
- }
-
- /**
- * Get WiFi AP's password
- *
- * @return String WiFi AP's password
- */
- public String getPassword()
- {
- if(mRep == null)
- {
- return null;
- }
-
- try
- {
- if(mRep.hasAttribute(ESConstants.OC_RSRVD_ES_CRED))
- return mRep.getValue(ESConstants.OC_RSRVD_ES_CRED);
- }
- catch (OcException e)
- {
- Log.e(TAG, "getPassword is failed.");
- }
- return null;
- }
-
- /**
- * Get WiFi AP's authenticate type
- * NONE_AUTH(0), WEP(1), WPA_PSK(2), WPA2_PSK(3)
- *
- * @return WIFI_AUTHTYPE WiFi AP's authenticate type
- */
- public WIFI_AUTHTYPE getAuthType()
- {
- if(mRep == null)
- {
- return WIFI_AUTHTYPE.NONE_AUTH;
- }
-
- try
- {
- if (mRep.hasAttribute(ESConstants.OC_RSRVD_ES_AUTHTYPE))
- return WIFI_AUTHTYPE.fromInt((int)mRep.getValue(ESConstants.OC_RSRVD_ES_AUTHTYPE));
- }
- catch (OcException e)
- {
- Log.e(TAG, "getAuthType is failed.");
- }
- return WIFI_AUTHTYPE.NONE_AUTH;
- }
-
- /**
- * Get WiFi AP's encryption type
- * NONE_ENC(0), WEP_64(1), WEP_128(2), TKIP(3), AES(4), TKIP_AES(5)
- *
- * @return WIFI_ENCTYPE WiFi AP's encryption type
- */
- public WIFI_ENCTYPE getEncType()
- {
- if(mRep == null)
- {
- return WIFI_ENCTYPE.NONE_ENC;
- }
-
- try
- {
- if (mRep.hasAttribute(ESConstants.OC_RSRVD_ES_ENCTYPE))
- return WIFI_ENCTYPE.fromInt((int)mRep.getValue(ESConstants.OC_RSRVD_ES_ENCTYPE));
- }
- catch (OcException e)
- {
- Log.e(TAG, "getEncType is failed.");
- }
- return WIFI_ENCTYPE.NONE_ENC;
- }
-
- /**
- * Get IETF language tag using ISO 639X
- *
- * @return String IETF language tag using ISO 639X
- */
- public String getLanguage()
- {
- if(mRep == null)
- {
- return null;
- }
-
- try
- {
- if(mRep.hasAttribute(ESConstants.OC_RSRVD_ES_LANGUAGE))
- return mRep.getValue(ESConstants.OC_RSRVD_ES_LANGUAGE);
- }
- catch (OcException e)
- {
- Log.e(TAG, "getLanguage is failed.");
- }
- return null;
- }
-
- /**
- * Get ISO Country Code (ISO 3166-1 Alpha-2)
- *
- * @return String ISO Country Code (ISO 3166-1 Alpha-2)
- */
- public String getCountry()
- {
- if(mRep == null)
- {
- return null;
- }
-
- try
- {
- if (mRep.hasAttribute(ESConstants.OC_RSRVD_ES_COUNTRY))
- return mRep.getValue(ESConstants.OC_RSRVD_ES_COUNTRY);
- }
- catch (OcException e)
- {
- Log.e(TAG, "getCountry is failed.");
- }
- return null;
- }
-
- /**
- * Get location info
- *
- * @return String location info of GPS
- */
- public String getLocation()
- {
- if(mRep == null)
- {
- return null;
- }
-
- try
- {
- if (mRep.hasAttribute(ESConstants.OC_RSRVD_ES_LOCATION))
- return mRep.getValue(ESConstants.OC_RSRVD_ES_LOCATION);
- }
- catch (OcException e)
- {
- Log.e(TAG, "getLocation is failed.");
- }
- return null;
- }
-
- public OcRepresentation toOCRepresentation()
- {
- return mRep;
- }
-}
+++ /dev/null
-/**
- * ***************************************************************
- *
- * Copyright 2016 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.iotivity.service.easysetup.mediator;
-
-import org.iotivity.service.easysetup.mediator.DevicePropProvisioningStatus;
-
-/**
- * This interface class is used as a callback function called after receiving
- * a response of device property provisioning result
- *
- * @see DevicePropProvisioningStatus
- */
-public abstract class DevicePropProvisioningCallback {
-
- /**
- * Called after receiving a response of device property provisioning result
- *
- * @param status a result of device property provisioning
- *
- * @see DevicePropProvisioningStatus
- */
- public abstract void onProgress(DevicePropProvisioningStatus status);
-}
+++ /dev/null
-/**
- * ***************************************************************
- *
- * Copyright 2016 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.iotivity.service.easysetup.mediator;
-
-import org.iotivity.service.easysetup.mediator.enums.ESResult;
-
-/**
- * This class indicates a result if a provisionDeviceProperties API succeed or fails
- */
-public class DevicePropProvisioningStatus
-{
- private ESResult m_result;
-
- /**
- * Constructor
- *
- * @param result a result if a provisionDeviceProperties API succeed or fails
- */
- public DevicePropProvisioningStatus(int result)
- {
- m_result = ESResult.fromInt(result);
- }
-
- /**
- * Get a result if a provisionDeviceProperties API succeed or fails
- *
- * @return ESResult a result if a provisionDeviceProperties API succeed or fails
- */
- public ESResult getESResult()
- {
- return m_result;
- }
-};
+++ /dev/null
-/**
- * ***************************************************************
- *
- * Copyright 2016 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.iotivity.service.easysetup.mediator;
-
-public class ESConstants {
-
- public static final String OC_RSRVD_REPRESENTATION = "rep";
-
- public static final String OC_RSRVD_ES_PROVSTATUS = "ps";
- public static final String OC_RSRVD_ES_LAST_ERRORCODE = "lec";
- public static final String OC_RSRVD_ES_LINKS = "links";
- public static final String OC_RSRVD_ES_SUPPORTEDWIFIMODE = "swmt";
- public static final String OC_RSRVD_ES_SUPPORTEDWIFIFREQ = "swf";
- public static final String OC_RSRVD_ES_SSID = "tnn";
- public static final String OC_RSRVD_ES_CRED = "cd";
- public static final String OC_RSRVD_ES_AUTHTYPE = "wat";
- public static final String OC_RSRVD_ES_ENCTYPE = "wet";
- public static final String OC_RSRVD_ES_AUTHCODE = "ac";
- public static final String OC_RSRVD_ES_ACCESSTOKEN = "at";
- public static final String OC_RSRVD_ES_ACCESSTOKEN_TYPE = "att";
- public static final String OC_RSRVD_ES_AUTHPROVIDER = "apn";
- public static final String OC_RSRVD_ES_CISERVER = "cis";
- public static final String OC_RSRVD_ES_SERVERID = "sid";
- public static final String OC_RSRVD_ES_DEVNAME = "dn";
- public static final String OC_RSRVD_ES_LANGUAGE = "lang";
- public static final String OC_RSRVD_ES_COUNTRY = "ctry";
- public static final String OC_RSRVD_ES_MODELNUMBER = "mnmo";
- public static final String OC_RSRVD_ES_LOCATION = "loc";
-
- public static final String OC_RSRVD_ES_VENDOR_DEVTYPE = "x.com.samsung.dt";
- public static final String OC_RSRVD_ES_VENDOR_DEVSUBTYPE = "x.com.samsung.sdt";
- public static final String OC_RSRVD_ES_VENDOR_DISCOVERYCHANNEL = "x.com.samsung.chn";
- public static final String SC_RSRVD_ES_VENDOR_LOCATION = "x.com.samsung.location";
-
-/**
-* Easysetup defined resoruce types and uris
-*/
- public static final String OC_RSRVD_ES_RES_TYPE_EASYSETUP = "oic.r.easysetup";
- public static final String OC_RSRVD_ES_URI_EASYSETUP = "/EasySetupResURI";
- public static final String OC_RSRVD_ES_RES_TYPE_WIFICONF = "oic.r.wificonf";
- public static final String OC_RSRVD_ES_URI_WIFICONF = "/WiFiConfResURI";
- public static final String OC_RSRVD_ES_RES_TYPE_COAPCLOUDCONF = "oic.r.coapcloudconf";
- public static final String OC_RSRVD_ES_URI_COAPCLOUDCONF = "/CoapCloudConfResURI";
- public static final String OC_RSRVD_ES_RES_TYPE_DEVCONF = "oic.r.devconf";
- public static final String OC_RSRVD_ES_URI_DEVCONF = "/DevConfResURI";
-
-}
+++ /dev/null
-/**
- * ***************************************************************
- * <p>
- * Copyright 2016 Samsung Electronics All Rights Reserved.
- * <p>
- * <p>
- * <p>
- * 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
- * <p>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p>
- * 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.
- * <p>
- * ****************************************************************
- */
-
-package org.iotivity.service.easysetup.mediator;
-
-/**
- * This is the Exception class for the EasySetup APIs
- */
-public class ESException extends Exception {
- public ESException(String exception) {
- super(exception);
- }
-}
+++ /dev/null
-/**
- * ***************************************************************
- *
- * Copyright 2017 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.iotivity.service.easysetup.mediator;
-
-import android.content.Context;
-import android.util.Log;
-
-import org.iotivity.base.OcConnectivityType;
-import org.iotivity.base.OcResource;
-import org.iotivity.base.OcPlatform;
-
-import java.util.ArrayList;
-import java.util.EnumSet;
-import java.util.List;
-
-/**
- * This provides an API to instanciate a new RemoteEnrollee object correspondent to Enrollee
- * Device to be setup.
- */
-public class EasySetup {
-
- private static final String TAG = EasySetup.class.getName();
- private static EasySetup sInstance;
-
- private static Context mContext;
-
- private ArrayList<RemoteEnrollee> mRemoteEnrolleeList;
-
- protected RemoteEnrollee mRemoteEnrollee;
-
- // function to call the native nativeCreateRemoteEnrollee
- private native RemoteEnrollee nativeCreateRemoteEnrollee(OcResource enrolleeResource);
- static {
- // Load Easy Setup JNI interface
- try
- {
- System.loadLibrary("ocprovision");
- } catch (UnsatisfiedLinkError e) {
- Log.i(TAG, "ocprovision library does not exist. (Unsecure mode)");
- }
-
- System.loadLibrary("ocstack-jni");
- System.loadLibrary("ESMediatorRich");
- System.loadLibrary("easysetup-jni");
- }
-
- private EasySetup() {
- mRemoteEnrolleeList = new ArrayList<RemoteEnrollee>();
- mContext = null;
- }
-
- /**
- * Gives a singleton instance of Easy setup and initialize the easy setup
- */
- public synchronized static EasySetup getInstance(Context context) {
- if (sInstance == null) {
- sInstance = new EasySetup();
- mContext = context;
- }
- return sInstance;
- }
-
- /**
- * This API is used for creating a remote Enrollee instance
- *
- * @param enrolleeResource an OCResource object corresponding to enrollee resource
- * discovered in a network. The OcResource object can be obtained by calling
- * OcPlatform.findResource() API. What resource you have to discover with
- * the OcPlatform.findResource() API is a "provisioning" resource with a certain
- * resource type, i.e. oic.r.easysetup
- *
- * @return Pointer to RemoteEnrollee instance
- */
- public synchronized RemoteEnrollee createRemoteEnrollee(OcResource enrolleeResource)
- {
- mRemoteEnrollee = nativeCreateRemoteEnrollee(enrolleeResource);
-
- if(mRemoteEnrollee != null)
- {
- mRemoteEnrolleeList.add(mRemoteEnrollee);
- return mRemoteEnrollee;
- }
- return null;
- }
-}
+++ /dev/null
-/**
- * ***************************************************************
- *
- * Copyright 2016 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.iotivity.service.easysetup.mediator;
-
-import android.util.Log;
-
-import org.iotivity.base.OcException;
-import org.iotivity.base.OcRepresentation;
-import org.iotivity.service.easysetup.mediator.ESConstants;
-import org.iotivity.service.easysetup.mediator.enums.WIFI_FREQ;
-import org.iotivity.service.easysetup.mediator.enums.WIFI_MODE;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-/**
- * This class stores Enrollee's configuration including WiFi and Device configuration
- * including supported WiFi frequency and device name
- */
-public class EnrolleeConf
-{
- private static final String TAG = EnrolleeConf.class.getName();
- protected OcRepresentation mEasySetupRep = null;
- /**
- * Constructor
- *
- * @param rep received properties in a form of OcRepresentation
- *
- */
- public EnrolleeConf(OcRepresentation rep)
- {
- mEasySetupRep = rep;
- }
-
- public EnrolleeConf(EnrolleeConf enrolleeConf)
- {
- mEasySetupRep = enrolleeConf.getEasySetupRep();
- }
-
- /**
- * Get Device Name property in DevConf resource
- *
- * @return deviceName
- */
- public String getDeviceName()
- {
- if(mEasySetupRep == null)
- {
- return null;
- }
-
- List<OcRepresentation> children = mEasySetupRep.getChildren();
-
- for (OcRepresentation child : children) {
- if(child.getUri().indexOf(ESConstants.OC_RSRVD_ES_URI_DEVCONF) != -1)
- {
- try
- {
- OcRepresentation rep;
- if(child.hasAttribute(ESConstants.OC_RSRVD_REPRESENTATION))
- {
- rep = (OcRepresentation)child.getValue(ESConstants.OC_RSRVD_REPRESENTATION);
- }
- else
- {
- return null;
- }
-
- if(rep.hasAttribute(ESConstants.OC_RSRVD_ES_DEVNAME)) {
- return (String) rep.getValue(ESConstants.OC_RSRVD_ES_DEVNAME);
- }
- } catch (OcException e) {
- Log.e(TAG, "getWiFiModes is failed.");
- }
- }
- }
- return null;
- }
-
- /**
- * Get Model Number property in DevConf resource
- *
- * @return modelNumber
- */
- public String getModelNumber()
- {
- if(mEasySetupRep == null)
- {
- return null;
- }
-
- List<OcRepresentation> children = mEasySetupRep.getChildren();
-
- for (OcRepresentation child : children) {
- if(child.getUri().indexOf(ESConstants.OC_RSRVD_ES_URI_DEVCONF) != -1)
- {
- try
- {
- OcRepresentation rep;
- if(child.hasAttribute(ESConstants.OC_RSRVD_REPRESENTATION))
- {
- rep = (OcRepresentation)child.getValue(ESConstants.OC_RSRVD_REPRESENTATION);
- }
- else
- {
- return null;
- }
-
- if(rep.hasAttribute(ESConstants.OC_RSRVD_ES_MODELNUMBER)) {
- return (String) rep.getValue(ESConstants.OC_RSRVD_ES_MODELNUMBER);
- }
- } catch (OcException e) {
- Log.e(TAG, "getModelNumber is failed.");
- }
- }
- }
- return null;
- }
-
- /**
- * Get Supported WiFi Modes property in WiFi resource
- *
- * @return a list of WiFi modes
- */
- public ArrayList<WIFI_MODE> getWiFiModes()
- {
- if(mEasySetupRep == null)
- {
- return null;
- }
-
- List<OcRepresentation> children = mEasySetupRep.getChildren();
- ArrayList<WIFI_MODE> modes = new ArrayList<WIFI_MODE>();
- for (OcRepresentation child : children) {
- if(child.getUri().indexOf(ESConstants.OC_RSRVD_ES_URI_WIFICONF) != -1)
- {
- try {
- OcRepresentation rep;
- if(child.hasAttribute(ESConstants.OC_RSRVD_REPRESENTATION))
- {
- rep = (OcRepresentation)child.getValue(ESConstants.OC_RSRVD_REPRESENTATION);
- }
- else
- {
- return null;
- }
-
- if (rep.hasAttribute(ESConstants.OC_RSRVD_ES_SUPPORTEDWIFIMODE)) {
- int modes_int[] = rep.getValue(ESConstants.OC_RSRVD_ES_SUPPORTEDWIFIMODE);
- for (int i = 0 ; i < modes_int.length ; ++i) {
- modes.add(WIFI_MODE.fromInt(modes_int[i]));
- }
- }
- } catch (OcException e) {
- Log.e(TAG, "getWiFiModes is failed.");
- }
- }
- }
- return modes;
- }
-
- /**
- * Get Supported WiFi frequency property in WiFi resource
- *
- * @return WiFi frequency
- */
- public WIFI_FREQ getWiFiFreq()
- {
- if(mEasySetupRep == null)
- {
- return WIFI_FREQ.WIFI_FREQ_NONE;
- }
-
- List<OcRepresentation> children = mEasySetupRep.getChildren();
-
- for (OcRepresentation child : children) {
- if(child.getUri().indexOf(ESConstants.OC_RSRVD_ES_URI_WIFICONF) != -1)
- {
- try{
- OcRepresentation rep;
- if(child.hasAttribute(ESConstants.OC_RSRVD_REPRESENTATION))
- {
- rep = (OcRepresentation)child.getValue(ESConstants.OC_RSRVD_REPRESENTATION);
- }
- else
- {
- return null;
- }
-
- if(rep.hasAttribute(ESConstants.OC_RSRVD_ES_SUPPORTEDWIFIFREQ))
- return WIFI_FREQ.fromInt(
- (int)rep.getValue(ESConstants.OC_RSRVD_ES_SUPPORTEDWIFIFREQ));
- } catch (OcException e) {
- Log.e(TAG, "getWiFiFreq is failed.");
- }
- }
- }
- return null;
- }
-
- /**
- * To check if Enrollee can access to cloud. To decide its preference, we check if a cloudserver
- * resource is registered on Enrollee.
- *
- * @return boolean
- */
- public boolean isCloudAccessible()
- {
- if(mEasySetupRep == null)
- {
- return false;
- }
-
- List<OcRepresentation> children = mEasySetupRep.getChildren();
-
- for (OcRepresentation child : children) {
- if(child.getUri().indexOf(ESConstants.OC_RSRVD_ES_URI_COAPCLOUDCONF) != -1)
- {
- return true;
- }
- }
- return false;
- }
-
- public OcRepresentation getEasySetupRep()
- {
- return mEasySetupRep;
- }
-}
-
-
+++ /dev/null
-/**
- * ***************************************************************
- *
- * Copyright 2016 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.iotivity.service.easysetup.mediator;
-
-import android.util.Log;
-
-import org.iotivity.base.OcException;
-import org.iotivity.base.OcRepresentation;
-import org.iotivity.service.easysetup.mediator.ESConstants;
-import org.iotivity.service.easysetup.mediator.enums.ESErrorCode;
-import org.iotivity.service.easysetup.mediator.enums.ProvStatus;
-
-/**
- * This class stores Enrollee's status including provisioning status and last error code.
- */
-public class EnrolleeStatus
-{
- private static final String TAG = EnrolleeStatus.class.getName();
- private OcRepresentation mRep = null;
- /**
- * Constructor
- *
- * @param rep received properties in a form of OcRepresentation
- *
- */
- public EnrolleeStatus(OcRepresentation rep)
- {
- mRep = rep;
- }
-
- /**
- * Get a provisioning status property of Enrollee.
- *
- * @return a provisioning status property of Enrollee
- */
- public ProvStatus getProvStatus()
- {
- try
- {
- if(mRep != null && mRep.hasAttribute(ESConstants.OC_RSRVD_ES_PROVSTATUS)) {
- int provStatus = mRep.getValue(ESConstants.OC_RSRVD_ES_PROVSTATUS);
- return ProvStatus.fromInt(provStatus);
- }
- } catch (OcException e) {
- Log.e(TAG, "getProvStatus is failed.");
- }
- return ProvStatus.fromInt(0);
- }
-
- /**
- * Get a last error code property of Enrollee.
- *
- * @return a last error code property of Enrollee.
- */
- public ESErrorCode getLastErrCode()
- {
- try
- {
- if(mRep != null && mRep.hasAttribute(ESConstants.OC_RSRVD_ES_LAST_ERRORCODE)) {
- int errCode = mRep.getValue(ESConstants.OC_RSRVD_ES_LAST_ERRORCODE);
- return ESErrorCode.fromInt(errCode);
- }
- } catch (OcException e) {
- Log.e(TAG, "getLastErrCode is failed.");
- }
- return ESErrorCode.fromInt(0);
- }
-}
-
-
+++ /dev/null
-/**
- * ***************************************************************
- *
- * Copyright 2016 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.iotivity.service.easysetup.mediator;
-
-/**
- * This interface class is used as a callback function called after receiving
- * Enrollee's configuration.
- *
- * @see GetConfigurationStatus
- */
-public abstract class GetConfigurationCallback {
-
- /**
- * Called after receiving Enrollee's configuration
- *
- * @param status
- * result if the request succeeds or fails
- * Enrollee's configuration like supported WiFi freq and device name
- */
- public abstract void onProgress(GetConfigurationStatus status);
-}
+++ /dev/null
-/**
- * ***************************************************************
- *
- * Copyright 2016 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.iotivity.service.easysetup.mediator;
-
-import org.iotivity.service.easysetup.mediator.enums.ESResult;
-
-/**
- * This class indicates a result if a getConfiguartion API succeed or fails and
- * Enrollee's configuration delivered by a response.
- */
-public class GetConfigurationStatus
-{
- private ESResult mResult;
- private EnrolleeConf mEnrolleeConf;
-
- /**
- * Constructor
- *
- * @param result a result if a getConfiguartion API succeed or fail
- * @param conf Enrollee's configuration
- *
- */
- public GetConfigurationStatus(int result, EnrolleeConf conf)
- {
- mResult = ESResult.fromInt(result);
- mEnrolleeConf = conf;
- }
-
- /**
- * Get a result of a getConfiguartion API call
- *
- * @return ESResult
- *
- */
- public ESResult getESResult()
- {
- return mResult;
- }
-
- /**
- * Get Enrollee's configuration
- *
- * @return EnrolleeConf includes a WiFi and Device configuration of Enrollee
- *
- * @see EnrolleeConf
- */
- public EnrolleeConf getEnrolleeConf()
- {
- return mEnrolleeConf;
- }
-};
+++ /dev/null
-/**
- * ***************************************************************
- *
- * Copyright 2016 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.iotivity.service.easysetup.mediator;
-
-import org.iotivity.service.easysetup.mediator.enums.ESResult;
-
-/**
- * This class indicates a result if a getConfiguartion API succeed or fails and
- * Enrollee's configuration delivered by a response.
- */
-public class GetEnrolleeStatus
-{
- private ESResult mResult;
- private EnrolleeStatus mEnrolleeStatus;
-
- /**
- * Constructor
- *
- * @param result a result if a getStatus API succeed or fail
- * @param status Enrollee's status
- *
- */
- public GetEnrolleeStatus(int result, EnrolleeStatus status)
- {
- mResult = ESResult.fromInt(result);
- mEnrolleeStatus = status;
- }
-
- /**
- * Get a result of a getStatus API call
- *
- * @return ESResult
- *
- */
- public ESResult getESResult()
- {
- return mResult;
- }
-
- /**
- * Get Enrollee's status
- *
- * @return EnrolleeStatus includes a provisioning status and last error code.
- *
- * @see EnrolleeStatus
- */
- public EnrolleeStatus getEnrolleeStatus()
- {
- return mEnrolleeStatus;
- }
-};
+++ /dev/null
-/**
- * ***************************************************************
- *
- * Copyright 2016 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.iotivity.service.easysetup.mediator;
-
-/**
- * This interface class is used as a callback function called after receiving
- * Enrollee's status.
- *
- * @see GetEnrolleeStatus
- */
-public abstract class GetStatusCallback {
-
- /**
- * Called after receiving Enrollee's status
- *
- * @param status
- * result if the request succeeds or fails
- * Enrollee's status like a provisioning status and last error code
- */
- public abstract void onProgress(GetEnrolleeStatus status);
-}
+++ /dev/null
-/**
- * ***************************************************************
- *
- * Copyright 2016 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.iotivity.service.easysetup.mediator;
-
-import android.util.Log;
-
-import org.iotivity.base.OcRepresentation;
-
-/**
- * This class represents Remote Enrollee device instance. What operations the class provides:
- * 1) Ownership transfer for enabling secured communication between Mediator and Enrollee
- * devices.
- * 2) Provision WiFi AP information used for which Enrollee is going to connect to the AP
- * 3) Provision Device confiruation setting, i.e. language, country, and etc
- * 4) Provision Cloud information used for which Enrollee is going to register to the cloud
- */
-public class RemoteEnrollee{
-
- public static final String TAG = RemoteEnrollee.class.getName();
- private long m_nativeHandle;
-
- private native void nativeGetStatus(GetStatusCallback callback);
- private native void nativeGetConfiguration(GetConfigurationCallback callback);
- private native void nativeProvisionSecurity(SecurityProvisioningCallback callback);
- private native void nativeProvisionDeviceProperties(OcRepresentation deviceProp,
- DevicePropProvisioningCallback callback);
- private native void nativeProvisionCloudProperties(OcRepresentation cloudProp, String cloudID,
- int CredID, CloudPropProvisioningCallback callback);
-
- /* constructor will be invoked from the native layer */
- private RemoteEnrollee(long nativeHandle){
- this.m_nativeHandle = nativeHandle;
- }
-
- /**
- * Get an Enrollee's status which includes a provisioning status and last error code
- *
- * @param callback will give the requested status
- *
- * @throws ESException If some errors happen in this function
- *
- * @see GetStatusCallback
- */
- public void getStatus(GetStatusCallback callback) throws ESException
- {
- if(callback != null)
- {
- nativeGetStatus(callback);
- return;
- }
- Log.d(TAG, "GetStatusCallback is null ");
- }
-
- /**
- * Get an Enrollee's configuration which includes WiFi supported frequency and device name
- *
- * @param callback will give the requested configuration
- *
- * @throws ESException If some errors happen in this function
- *
- * @see GetConfigurationCallback
- */
- public void getConfiguration(GetConfigurationCallback callback)
- throws ESException
- {
- if(callback != null)
- {
- nativeGetConfiguration(callback);
- return;
- }
- Log.d(TAG, "GetConfigurationCallback is null ");
- }
-
- /**
- * Do security provisioning such as ownership tranfer to Enrollee.
- *
- * @param callback will give the result if the security provisioning succeeds or fails for some reasons
- *
- * @throws ESException If some errors happen in this function
- *
- * @see SecurityProvisioningCallback
- */
- public void provisionSecurity(SecurityProvisioningCallback callback)
- throws ESException
- {
- if(callback != null)
- {
- nativeProvisionSecurity(callback);
- return;
- }
- Log.d(TAG, "SecurityProvisioningCallback is null ");
- }
-
- /**
- * Provision WiFi AP information and device configuration to Enrollee
- * 1. WiFi AP information includes a SSID, password, auth type, and encryption type.
- * 2. Device configuration includes a language (IETF language tags) and country (ISO 3166-1 Alpha-2)
- *
- * @param deviceProp a data structure storing the above information to be delivered
- * @param callback will give the result if the provisioning succeeds or fails
- *
- * @throws ESException If some errors happen in this function
- *
- * @see DeviceProp
- * @see DevicePropProvisioningCallback
- */
- public void provisionDeviceProperties(DeviceProp deviceProp,
- DevicePropProvisioningCallback callback) throws ESException{
- if(callback != null)
- {
- nativeProvisionDeviceProperties(deviceProp.toOCRepresentation(),
- callback);
- return;
- }
- Log.d(TAG, "DevicePropProvisioningCallback is null ");
- }
-
- /**
- * Provision Cloud information to Enrollee, which includes Auth code, auth provider,
- * Cloud interface server URL, and etc.
- * In this function, Discovery for the Enrollee will happen again in a given network.
- * Because, this function is expected to call *AFTER* the Enrollee disconnects its Soft AP
- * and successfully connects to the certain WiFi AP. In that case, Mediator should discover
- * the Enrollee with a certain Device ID in the network.
- *
- * @param cloudProp a data structure storing the above information to be delivered
- * @param callback will give the result if the provisioning succeeds or fails
- *
- * @throws ESException If some errors happen in this function
- *
- * @see CloudProp
- * @see CloudPropProvisioningCallback
- */
- public void provisionCloudProperties(CloudProp cloudProp,
- CloudPropProvisioningCallback callback) throws ESException{
- if(callback != null)
- {
- nativeProvisionCloudProperties(cloudProp.toOCRepresentation(),
- cloudProp.getCloudID(),
- cloudProp.getCredID(),
- callback);
- return;
- }
- Log.d(TAG, "CloudPropProvisioningCallback is null ");
- }
-}
+++ /dev/null
-/**
- * ***************************************************************
- *
- * Copyright 2016 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.iotivity.service.easysetup.mediator;
-
-import org.iotivity.service.easysetup.mediator.SecurityProvisioningStatus;
-
-/**
- * This interface class is used as a callback function called after receiving
- * Security provisioning result
- *
- * @see SecurityProvisioningStatus
- */
-public abstract class SecurityProvisioningCallback {
-
- /**
- * Called after receiving Security provisioning result
- *
- * @param status
- * a result of security provisioning
- * a device ID of a target Enrollee even if security provisioning
- * is failed for some reasons
- *
- * @see SecurityProvisioningStatus
- */
- public abstract void onProgress(SecurityProvisioningStatus status);
-}
+++ /dev/null
-/**
- * ***************************************************************
- *
- * Copyright 2016 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.iotivity.service.easysetup.mediator;
-
-import android.util.Log;
-
-import org.iotivity.service.easysetup.mediator.enums.ESResult;
-
-/**
- * This class indicates a result if a provisionSecurity API succeed or fails and
- * a target Enrollee's device ID
- */
-public class SecurityProvisioningStatus
-{
- private ESResult mResult;
- private String mDevUUID;
-
- /**
- * Constructor
- *
- * @param result a result of security provisioning
- * @param uuid a device ID of a target Enrollee
- */
- public SecurityProvisioningStatus(int result, String uuid)
- {
- mResult = ESResult.fromInt(result);
- mDevUUID = uuid;
- }
-
- /**
- * Get a Result of security provisioning
- *
- * @return ESResult a result of security provisioning
- */
- public ESResult getESResult()
- {
- return mResult;
- }
-
- /**
- * Get a device ID of a target Enrollee
- *
- * @return String a device ID of a target Enrollee
- */
- public String getDevUUID()
- {
- return mDevUUID;
- }
-};
+++ /dev/null
-/**
- * ***************************************************************
- *
- * Copyright 2016 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.iotivity.service.easysetup.mediator.enums;
-
-/**
- * It defines various states of the cloud provisioning during easy setup process
- */
-public enum ESCloudProvState {
-
- /**
- * Some error occurs during cloud data provisioning
- */
- ES_CLOUD_PROVISIONING_ERROR(-1),
-
- /**
- * Cloud data provisioning is successfully done
- */
- ES_CLOUD_PROVISIONING_SUCCESS(0),
-
- /**
- * Target enrollee which needs a cloud provisioning is found in a network
- */
- ES_CLOUD_ENROLLEE_FOUND(1),
-
- /**
- * Target enrollee which needs a cloud provisioning is NOT found in a network
- */
- ES_CLOUD_ENROLLEE_NOT_FOUND(2);
-
- private int value;
-
- private ESCloudProvState(int value) {
- this.value = value;
- }
-
- public int getValue() {
- return value;
- }
-
- public static ESCloudProvState fromInt(int i) {
- for (ESCloudProvState b : ESCloudProvState.values()) {
- if (b.getValue() == i) { return b; }
- }
- return null;
- }
-};
-
+++ /dev/null
-/**
- * ***************************************************************
- *
- * Copyright 2016 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.iotivity.service.easysetup.mediator.enums;
-
-/**
- * @brief Indicate last error code to describe a reason of error during easy setup.
- */
-public enum ESErrorCode {
-
- /**
- * Init Error Code
- */
- ES_ERRCODE_NO_ERROR(0),
-
- /**
- * Error Code that given WiFi's SSID is not found
- */
- ES_ERRCODE_SSID_NOT_FOUND(1),
-
- /**
- * Error Code that given WiFi's Password is wrong
- */
- ES_ERRCODE_PW_WRONG(2),
-
- /**
- * Error Code that IP address is not allocated
- */
- ES_ERRCODE_IP_NOT_ALLOCATED(3),
-
- /**
- * Error Code that there is no Internet connection
- */
- ES_ERRCODE_NO_INTERNETCONNECTION(4),
-
- /**
- * Error Code that Timeout occured
- */
- ES_ERRCODE_TIMEOUT(5),
-
- /**
- * Error Code that cloud server is not reachable due to wrong URL of cloud server, for example.
- */
- ES_ERRCODE_FAILED_TO_ACCESS_CLOUD_SERVER(6),
-
- /**
- * Error Code that no response is arrived from cloud server
- */
- ES_ERRCODE_NO_RESPONSE_FROM_CLOUD_SERVER(7),
-
- /**
- * Error Code that a delivered authcode is not valid.
- */
- ES_ERRCODE_INVALID_AUTHCODE(8),
-
- /**
- * Error Code that a given access token is not valid due to its expiration, for example.
- */
- ES_ERRCODE_INVALID_ACCESSTOKEN(9),
-
- /**
- * Error Code that a refresh of expired access token is failed due to some reasons.
- */
- ES_ERRCODE_FAILED_TO_REFRESH_ACCESSTOKEN(10),
-
- /**
- * Error Code that a target device is not discovered in cloud server
- */
- ES_ERRCODE_FAILED_TO_FIND_REGISTERED_DEVICE_IN_CLOUD(11),
-
- /**
- * Error Code that a target user does not exist in cloud server.
- */
- ES_ERRCODE_FAILED_TO_FIND_REGISTERED_USER_IN_CLOUD(12),
-
- /**
- * Error Code that Unknown error occured
- */
- ES_ERRCODE_UNKNOWN(255);
-
- private int value;
-
- private ESErrorCode(int value) {
- this.value = value;
- }
-
- public int getValue() {
- return value;
- }
-
- public static ESErrorCode fromInt(int i) {
- for (ESErrorCode b : ESErrorCode.values()) {
- if (b.getValue() == i) { return b; }
- }
- return null;
- }
-};
-
+++ /dev/null
-/**
- * ***************************************************************
- *
- * Copyright 2016 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.iotivity.service.easysetup.mediator.enums;
-
-/**
- * It defines an result during easy setup process, which is same as one in Easy Setup C++ SDK
- */
-public enum ESResult {
-
- ES_OK(0),
- ES_ENROLLEE_DISCOVERY_FAILURE(11),
- ES_COMMUNICATION_ERROR(12),
- ES_SEC_OPERATION_IS_NOT_SUPPORTED(20),
- ES_SECURE_RESOURCE_DISCOVERY_FAILURE(21),
- ES_OWNERSHIP_TRANSFER_FAILURE(22),
- ES_ACL_PROVISIONING_FAILURE(23),
- ES_CERT_PROVISIONING_FAILURE(24),
- ES_ERROR(255);
-
- private int value;
-
- private ESResult(int value) {
- this.value = value;
- }
-
- public int getValue() {
- return value;
- }
-
- public static ESResult fromInt(int i) {
- for (ESResult b : ESResult.values()) {
- if (b.getValue() == i) { return b; }
- }
- return null;
- }
-};
\ No newline at end of file
+++ /dev/null
-/**
- * ***************************************************************
- *
- * Copyright 2016 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.iotivity.service.easysetup.mediator.enums;
-
-/**
- * This enum class indicates an OAuth Token type like "bearer" and "mac"\r
- */
-public enum OAUTH_TOKENTYPE\r
-{
- NONE_OAUTH_TOKENTYPE(0),\r
- OAUTH_TOKENTYPE_BEARER(1),\r
- OAUTH_TOKENTYPE_MAC(2);\r
-\r
- private int value;
-
- private OAUTH_TOKENTYPE(int value)\r
- {
- this.value = value;
- }
-
- /**
- * Get OAuth Token type as an integer value\r
- *
- * @return int OAuth Token type as an integer value\r
- */
- public int getValue()
- {
- return value;
- }
-
- /**
- * Get OAuth Token type as OAUTH_TOKENTYPE type value\r
- *
- * @return OAuth Token type enum value corresponding to its integer value\r
- */
- public static OAUTH_TOKENTYPE fromInt(int i)\r
- {
- for (OAUTH_TOKENTYPE b : OAUTH_TOKENTYPE.values())\r
- {
- if (b.getValue() == i)
- return b;
- }
- return null;
- }
-}
-\r
+++ /dev/null
-/**
- * ***************************************************************
- *
- * Copyright 2016 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.iotivity.service.easysetup.mediator.enums;
-
-/**
- * It defines various states of the cloud provisioning during easy setup process
- */
-public enum ProvStatus {
-
- /**
- * Default state of the device
- */
- ES_STATE_INIT(0),
-
- /**
- * Status indicating being connecting to target network
- */
- ES_STATE_CONNECTING_TO_ENROLLER(1),
-
- /**
- * Status indicating successful connection to target network
- */
- ES_STATE_CONNECTED_TO_ENROLLER(2),
-
- /**
- * Status indicating failure connection to target network
- */
- ES_STATE_FAILED_TO_CONNECT_TO_ENROLLER(3),
-
- /**
- * Status indicating being registering to cloud
- */
- ES_STATE_REGISTERING_TO_CLOUD(4),
-
- /**
- * Status indicating successful registration to cloud
- */
- ES_STATE_REGISTERED_TO_CLOUD(5),
-
- /**
- * Status indicating registeration failure to cloud
- */
- ES_STATE_FAILED_TO_REGISTER_TO_CLOUD(6),
-
- /**
- * Status indicating being publishing resources to cloud
- */
- ES_STATE_PUBLISHING_RESOURCES_TO_CLOUD(7),
-
- /**
- * Status indicating successful resource publish to cloud
- */
- ES_STATE_PUBLISHED_RESOURCES_TO_CLOUD(8),
-
- /**
- * Status indicating resource publish failure to cloud
- */
- ES_STATE_FAILED_TO_PUBLISH_RESOURCES_TO_CLOUD(9),
-
- /**
- * End of Easy setup status
- */
- ES_STATE_EOF(255);
-
- private int value;
-
- private ProvStatus(int value) {
- this.value = value;
- }
-
- public int getValue() {
- return value;
- }
-
- public static ProvStatus fromInt(int i) {
- for (ProvStatus b : ProvStatus.values()) {
- if (b.getValue() == i) { return b; }
- }
- return null;
- }
-};
-
+++ /dev/null
-/**
- * ***************************************************************
- *
- * Copyright 2016 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.iotivity.service.easysetup.mediator.enums;
-
-/**
- * This enum class indicates a WiFi authentication type
- */
-public enum WIFI_AUTHTYPE
-{
- NONE_AUTH(0),
- WEP(1),
- WPA_PSK(2),
- WPA2_PSK(3);
-
- private int value;
-
- private WIFI_AUTHTYPE(int value)
- {
- this.value = value;
- }
-
- public int getValue()
- {
- return value;
- }
-
- public static WIFI_AUTHTYPE fromInt(int i)
- {
- for (WIFI_AUTHTYPE b : WIFI_AUTHTYPE.values())
- {
- if (b.getValue() == i)
- return b;
- }
- return null;
- }
-}
+++ /dev/null
-/**
- * ***************************************************************
- *
- * Copyright 2016 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.iotivity.service.easysetup.mediator.enums;
-
-/**
- * This enum class indicates a WiFi encryption type
- */
-public enum WIFI_ENCTYPE
-{
- NONE_ENC(0),
- WEP_64(1),
- WEP_128(2),
- TKIP(3),
- AES(4),
- TKIP_AES(5);
-
- private int value;
-
- private WIFI_ENCTYPE(int value)
- {
- this.value = value;
- }
-
- public int getValue()
- {
- return value;
- }
-
- public static WIFI_ENCTYPE fromInt(int i)
- {
- for (WIFI_ENCTYPE b : WIFI_ENCTYPE.values())
- {
- if (b.getValue() == i)
- return b;
- }
- return null;
- }
-}
+++ /dev/null
-/**
- * ***************************************************************
- *
- * Copyright 2016 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.iotivity.service.easysetup.mediator.enums;
-
-/**
- * This enum class indicates a WiFi frequency like 2.4G and 5G
- */
-public enum WIFI_FREQ
-{
- WIFI_24G(0),
- WIFI_5G(1),
- WIFI_BOTH(2),
- WIFI_FREQ_NONE(999);
-
- private int value;
-
- private WIFI_FREQ(int value)
- {
- this.value = value;
- }
-
- /**
- * Get WiFi frequency as an integer value
- *
- * @return int WiFi freq. as an integer value
- */
- public int getValue()
- {
- return value;
- }
-
- /**
- * Get WiFi frequency as an integer value
- *
- * @return WIFI_FREQ enum value corresponding to its integer value
- */
- public static WIFI_FREQ fromInt(int i)
- {
- for (WIFI_FREQ b : WIFI_FREQ.values())
- {
- if (b.getValue() == i)
- return b;
- }
- return null;
- }
-}
+++ /dev/null
-/**
- * ***************************************************************
- *
- * Copyright 2016 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.iotivity.service.easysetup.mediator.enums;
-
-/**
- * This enum class indicates a WiFi mode like 11A and 11N.
- */
-public enum WIFI_MODE
-{
- /**
- * 801.11A
- */
- WIFI_11A(0),
-
- /**
- * 801.11B
- */
- WIFI_11B(1),
-
- /**
- * 801.11G
- */
- WIFI_11G(2),
-
- /**
- * 801.11N
- */
- WIFI_11N(3),
-
- /**
- * 801.11AC
- */
- WIFI_11AC(4);
-
- private int value;
-
- private WIFI_MODE(int value)
- {
- this.value = value;
- }
-
- /**
- * Get WiFi mode as an integer value
- *
- * @return int WiFi mode as an integer value
- */
- public int getValue()
- {
- return value;
- }
-
- /**
- * Convert integer to WIFI_MODE enum value
- *
- * @param i An integer value converting
- * @return WIFI_MODE enum value corresponding to its integer value
- */
- public static WIFI_MODE fromInt(int i)
- {
- for (WIFI_MODE b : WIFI_MODE.values())
- {
- if (b.getValue() == i)
- return b;
- }
- return null;
- }
-}
+++ /dev/null
-/**
- * ***************************************************************
- *
- * Copyright 2016 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.iotivity.service.easysetup.mediator.samsung;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-
-import android.util.Log;
-
-import org.iotivity.service.easysetup.mediator.DeviceProp;
-import org.iotivity.service.easysetup.mediator.ESConstants;
-import org.iotivity.service.easysetup.mediator.enums.WIFI_AUTHTYPE;
-import org.iotivity.service.easysetup.mediator.enums.WIFI_ENCTYPE;
-
-import org.iotivity.base.OcException;
-import org.iotivity.base.OcRepresentation;
-
-/**
- * This class contains device properties to be delivered to Enrollee
- */
-public class SCDeviceProp extends DeviceProp {
- private static final String TAG = SCDeviceProp.class.getName();
- final int INVALID_DISCOVERY_CHANNEL = -1;
-
- /**
- * Set Channel of Enroller for fast discover
- */
- public void setDiscoveryChannel(int discoveryChannel)
- {
- try
- {
- mRep.setValue(ESConstants.OC_RSRVD_ES_VENDOR_DISCOVERYCHANNEL, discoveryChannel);
- } catch (OcException e) {
- Log.e(TAG, "setDiscoveryChannel is failed.");
- }
- }
-
- /**
- * Get Channel of Enroller for fast discover
- *
- * @return int Enroller's DiscoveryChannel
- */
- public int getDiscoveryChannel()
- {
- try {
- if(mRep.hasAttribute(ESConstants.OC_RSRVD_ES_VENDOR_DISCOVERYCHANNEL))
- return mRep.getValue(ESConstants.OC_RSRVD_ES_VENDOR_DISCOVERYCHANNEL);
- } catch (OcException e) {
- Log.e(TAG, "getDiscoveryChannel is failed.");
- }
- return INVALID_DISCOVERY_CHANNEL;
- }
-
- /**
- * Set samsung-specific location property to be delivered to Enrollee
- *
- * @param locations a set of location information
- */
- public void setSCLocation(ArrayList<String> locations)
- {
- try
- {
- mRep.setValue(ESConstants.SC_RSRVD_ES_VENDOR_LOCATION, locations.toArray(new
- String[locations.size()]));
- } catch (OcException e) {
- Log.e(TAG, "setSCLocation is failed.");
- }
- }
-}
+++ /dev/null
-/**
- * ***************************************************************
- *
- * Copyright 2016 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.iotivity.service.easysetup.mediator.samsung;
-
-import android.util.Log;
-
-import org.iotivity.base.OcException;
-import org.iotivity.base.OcRepresentation;
-import org.iotivity.service.easysetup.mediator.ESConstants;
-import org.iotivity.service.easysetup.mediator.EnrolleeConf;
-
-import java.util.List;
-
-/**
- * This class stores Enrollee's configuration including WiFi and Device configuration
- * including supported WiFi frequency and device name
- */
-public class SCEnrolleeConf extends EnrolleeConf
-{
- private static final String TAG = SCEnrolleeConf.class.getName();
-
- /**
- * Constructor
- *
- * @param rep received properties in a form of OcRepresentation
- */
- public SCEnrolleeConf(EnrolleeConf enrolleeConf) {
- super(enrolleeConf);
- }
-
- /**
- * Get Device type property in DevConf resource
- *
- * @return device type
- */
- public String getDeviceType()
- {
- List<OcRepresentation> children = mEasySetupRep.getChildren();
-
- for (OcRepresentation child : children) {
- if(child.getUri().indexOf(ESConstants.OC_RSRVD_ES_URI_DEVCONF) != -1)
- {
- try
- {
- if(child.hasAttribute(ESConstants.OC_RSRVD_ES_VENDOR_DEVTYPE)) {
- return (String) child.getValue(ESConstants.OC_RSRVD_ES_VENDOR_DEVTYPE);
- }
- } catch (OcException e) {
- Log.e(TAG, "getDeviceType is failed.");
- }
- }
- }
- return new String("");
- }
-
- /**
- * Get Device sub-type property in DevConf resource
- *
- * @return device sub-type
- */
- public String getDeviceSubType()
- {
- List<OcRepresentation> children = mEasySetupRep.getChildren();
-
- for (OcRepresentation child : children) {
- if(child.getUri().indexOf(ESConstants.OC_RSRVD_ES_URI_DEVCONF) != -1)
- {
- try
- {
- if(child.hasAttribute(ESConstants.OC_RSRVD_ES_VENDOR_DEVSUBTYPE)) {
- return (String) child.getValue(ESConstants.OC_RSRVD_ES_VENDOR_DEVSUBTYPE);
- }
- } catch (OcException e) {
- Log.e(TAG, "getDeviceType is failed.");
- }
- }
- }
- return new String("");
- }
-}
-
-
+++ /dev/null
-#//******************************************************************
-#//
-#// Copyright 2016 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.
-#//
-#//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-LOCAL_PATH := $(call my-dir)
-SECURED := $(SECURE)
-
-include $(CLEAR_VARS)
-OIC_LIB_PATH := ../../../../../../../../../out/android/$(TARGET_ARCH_ABI)/$(APP_OPTIM)
-LOCAL_MODULE := android-oc
-LOCAL_SRC_FILES := $(OIC_LIB_PATH)/liboc.so
-include $(PREBUILT_SHARED_LIBRARY)
-
-include $(CLEAR_VARS)
-OIC_LIB_PATH := ../../../../../../../../../out/android/$(TARGET_ARCH_ABI)/$(APP_OPTIM)
-LOCAL_MODULE := android-easysetup
-LOCAL_SRC_FILES := $(OIC_LIB_PATH)/libESMediatorRich.so
-include $(PREBUILT_SHARED_LIBRARY)
-
-ifeq ($(SECURED), 1)
-include $(CLEAR_VARS)
-OIC_LIB_PATH := ../../../../../../../../../out/android/$(TARGET_ARCH_ABI)/$(APP_OPTIM)
-LOCAL_MODULE := android-ocprovision
-LOCAL_SRC_FILES := $(OIC_LIB_PATH)/libocprovision.so
-include $(PREBUILT_SHARED_LIBRARY)
-endif
-
-include $(CLEAR_VARS)
-OIC_LIB_PATH := ../../../../../../../../../android/android_api/base/libs/$(TARGET_ARCH_ABI)
-LOCAL_MODULE := android-ocstack
-LOCAL_SRC_FILES := $(OIC_LIB_PATH)/libocstack-jni.so
-include $(PREBUILT_SHARED_LIBRARY)
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := easysetup-jni
-
-#Add Pre processor definitions
-DEFINE_FLAG = -DWITH_POSIX -D__ANDROID__
-
-#Add Debug flags here
-DEBUG_FLAG = -DTB_LOG
-
-BUILD_FLAG = $(DEFINE_FLAG) $(DEBUG_FLAG)
-
-LOCAL_CPPFLAGS = $(BUILD_FLAG)
-LOCAL_CPPFLAGS += -std=c++0x -frtti -fexceptions
-
-$(info CPPFLAGSUPDATED=$(LOCAL_CPPFLAGS))
-
-LOCAL_C_INCLUDES := $(LOCAL_PATH) \
- $(LOCAL_PATH)/../../../../../inc \
- $(LOCAL_PATH)/../../../../../src \
- $(LOCAL_PATH)/../../../../../../../inc \
- $(LOCAL_PATH)/../../../../../../../../../resource/csdk/logger/include \
- $(LOCAL_PATH)/../../../../../../../../../resource/csdk/connectivity/common/inc \
- $(LOCAL_PATH)/../../../../../../../../../resource/c_common/oic_string/include \
- $(LOCAL_PATH)/../../../../../../../../../resource/include \
- $(LOCAL_PATH)/../../../../../../../../../resource/c_common \
- $(LOCAL_PATH)/../../../../../../../../../resource/oc_logger/include \
- $(LOCAL_PATH)/../../../../../../../../../resource/c_common/oic_malloc/include \
- $(LOCAL_PATH)/../../../../../../../../../resource/csdk/connectivity/api \
- $(LOCAL_PATH)/../../../../../../../../../resource/csdk/stack/include \
- $(LOCAL_PATH)/../../../../../../../../../resource/csdk/logger/include \
- $(LOCAL_PATH)/../../../../../../../../../resource/csdk/security/include \
- $(LOCAL_PATH)/../../../../../../../../../resource/csdk/security/provisioning/include \
- $(LOCAL_PATH)/../../../../../../../../../resource/csdk/security/provisioning/include/cloud \
- $(LOCAL_PATH)/../../../../../../../../../resource/csdk/security/provisioning/include/oxm \
- $(LOCAL_PATH)/../../../../../../../../../extlibs/cjson \
- $(LOCAL_PATH)/../../../../../../../../../extlibs/boost/boost_1_58_0 \
- $(LOCAL_PATH)/../../../../../../../../../extlibs/timer \
- $(LOCAL_PATH)/../../../../../../../../../android/android_api/base/jni \
-
-LOCAL_SRC_FILES += $(patsubst $(LOCAL_PATH)/%, %, $(wildcard $(LOCAL_PATH)/*.cpp))
-LOCAL_SRC_FILES += $(patsubst $(LOCAL_PATH)/%, %, $(wildcard $(LOCAL_PATH)/*.h))
-
-LOCAL_LDLIBS := -llog
-#LOCAL_SHARED_LIBRARIES += android-connectivity_abstraction
-LOCAL_SHARED_LIBRARIES += android-ocstack
-ifeq ($(SECURED), 1)
-LOCAL_SHARED_LIBRARIES += android-ocprovision
-endif
-LOCAL_SHARED_LIBRARIES += android-oc
-LOCAL_SHARED_LIBRARIES += android-easysetup
-
-include $(BUILD_SHARED_LIBRARY)
+++ /dev/null
-#//******************************************************************
-#//
-#// Copyright 2016 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.
-#//
-#//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-APP_STL := gnustl_shared
-APP_PLATFORM = android-21
-NDK_TOOLCHAIN_VERSION := 4.8
-
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2016 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 "JniCloudPropProvisioningStatusListener.h"
-#include "JniRemoteEnrollee.h"
-
-using namespace OIC::Service;
-
-JniCloudPropProvisioningStatusListener::JniCloudPropProvisioningStatusListener(JNIEnv *env, jobject jListener,
- JniRemoteEnrollee *owner)
- : m_ownerResource(owner)
-{
- m_jwListener = env->NewWeakGlobalRef(jListener);
-}
-
-JniCloudPropProvisioningStatusListener::~JniCloudPropProvisioningStatusListener()
-{
- ES_LOGI("~JniCloudPropProvisioningStatusListener()");
- if (m_jwListener)
- {
- jint ret;
- JNIEnv *env = GetESJNIEnv(ret);
- if (NULL == env) return;
- env->DeleteWeakGlobalRef(m_jwListener);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
- }
-}
-
-void JniCloudPropProvisioningStatusListener::onCloudPropProvisioningStatus(std::shared_ptr<CloudPropProvisioningStatus>
- cloudPropProvisioningStatus)
-{
-
- ES_LOGI("JniCloudPropProvisioningStatusListener::onCloudPropProvisioningStatus enter");
-
- jint ret;
- JNIEnv *env = GetESJNIEnv(ret);
- if (NULL == env) return;
- jobject jListener = env->NewLocalRef(m_jwListener);
- if (!jListener)
- {
- checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
- return;
- }
-
- jclass clsL = env->GetObjectClass(jListener);
- if (!clsL)
- {
- checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
- return;
- }
-
- jmethodID midL = env->GetMethodID(clsL, "onProgress",
- "(Lorg/iotivity/service/easysetup/mediator/"
- "CloudPropProvisioningStatus;"
- ")V");
- if (!midL)
- {
- checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
- return;
- }
-
- ESResult esResult = cloudPropProvisioningStatus->getESResult();
-
- //create the java object
- jobject jCloudPropProvisioningStatus = NULL;
- jCloudPropProvisioningStatus = env->NewObject(g_cls_CloudPropProvisioningStatus,
- g_mid_CloudPropProvisioningStatus_ctor,
- (jint)esResult);
-
- ES_LOGI("JniCloudPropProvisioningStatus::onCloudPropProvisioningStatus - %d", esResult);
- if (!jCloudPropProvisioningStatus)
- {
- ES_LOGE("JniCloudPropProvisioningStatus::onCloudPropProvisioningStatus Unable to create the java object");
- return ;
- }
-
- env->CallVoidMethod(jListener, midL, jCloudPropProvisioningStatus);
-
- bool needRemoveListener = false;
-
- if(esResult == ES_OK)
- {
- needRemoveListener = true;
- }
-
- if (env->ExceptionCheck())
- {
- ES_LOGE("Java exception is thrown");
- if(needRemoveListener)
- checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
- return;
- }
-
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
-}
-
-void JniCloudPropProvisioningStatusListener::checkExAndRemoveListener(JNIEnv *env)
-{
- if (env->ExceptionCheck())
- {
- jthrowable ex = env->ExceptionOccurred();
- env->ExceptionClear();
- m_ownerResource->removeStatusListener<JniCloudPropProvisioningStatusListener>(env, m_jwListener);
- env->Throw((jthrowable)ex);
- }
- else
- {
- m_ownerResource->removeStatusListener<JniCloudPropProvisioningStatusListener>(env, m_jwListener);
- }
-}
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2016 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.
- *
- ******************************************************************/
-/** @file JniProvisioningStatusListener.h
- *
- * @brief This file contains JNI Provisioing status Listener class
- */
-
-#ifndef __JNI_ES_CLOUD_PROP_PROVISIONING_STATUS_LISTENER_H_
-#define __JNI_ES_CLOUD_PROP_PROVISIONING_STATUS_LISTENER_H_
-
-#include <jni.h>
-
-#include "RemoteEnrollee.h"
-#include "ESRichCommon.h"
-
-#include "JniJvm.h"
-
-class JniRemoteEnrollee;
-
-using namespace OIC::Service;
-
-/**
- * @class JniCloudPropProvisioningStatusListener
- * @brief This class provides functions for handling the cloud provisioning status callback between the Java and native layer
- *
- */
-class JniCloudPropProvisioningStatusListener
-{
- public:
- /**
- * @brief constructor
- */
- JniCloudPropProvisioningStatusListener(JNIEnv *env, jobject jListener, JniRemoteEnrollee *resource);
-
- /**
- * @brief destructor
- */
- ~JniCloudPropProvisioningStatusListener();
-
- /**
- * @brief callback function that will be passed to Native layer
- */
- void onCloudPropProvisioningStatus (std::shared_ptr<CloudPropProvisioningStatus> cloudPropProvisioningStatus);
-
- private:
- jweak m_jwListener;
- JniRemoteEnrollee *m_ownerResource;
- void checkExAndRemoveListener(JNIEnv *env);
-};
-
-#endif //__JNI_ES_CLOUD_PROP_PROVISIONING_STATUS_LISTENER_H_
-
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2016 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 "JniDevicePropProvisioningStatusListener.h"
-#include "JniRemoteEnrollee.h"
-
-using namespace OIC::Service;
-
-JniDevicePropProvisioningStatusListener::JniDevicePropProvisioningStatusListener(JNIEnv *env, jobject jListener,
- JniRemoteEnrollee *owner)
- : m_ownerResource(owner)
-{
- m_jwListener = env->NewWeakGlobalRef(jListener);
-}
-
-JniDevicePropProvisioningStatusListener::~JniDevicePropProvisioningStatusListener()
-{
- ES_LOGI("~JniDevicePropProvisioningStatusListener()");
- if (m_jwListener)
- {
- jint ret;
- JNIEnv *env = GetESJNIEnv(ret);
- if (NULL == env) return;
- env->DeleteWeakGlobalRef(m_jwListener);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
- }
-}
-
-void JniDevicePropProvisioningStatusListener::onDevicePropProvisioningStatusCallback (std::shared_ptr<DevicePropProvisioningStatus>
- devicePropProvStatusCb)
-{
-
- ES_LOGI("JniDevicePropProvisioningStatusListener::onDevicePropProvisioningStatusCallback enter");
-
- jint ret;
- JNIEnv *env = GetESJNIEnv(ret);
- if (NULL == env) return;
- jobject jListener = env->NewLocalRef(m_jwListener);
- if (!jListener)
- {
- checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
- return;
- }
-
- jclass clsL = env->GetObjectClass(jListener);
- if (!clsL)
- {
- checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
- return;
- }
- //TODO:
- jmethodID midL = env->GetMethodID(clsL, "onProgress",
- "(Lorg/iotivity/service/easysetup/mediator/"
- "DevicePropProvisioningStatus;"
- ")V");
-
- if (!midL)
- {
- checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
- return;
- }
-
- ESResult esResult = devicePropProvStatusCb->getESResult();
-
- jobject jDevicePropProvisioningStatus = NULL;
- jDevicePropProvisioningStatus = env->NewObject(g_cls_DevicePropProvisioningStatus,
- g_mid_DevicePropProvisioningStatus_ctor,
- (jint)esResult);
-
- ES_LOGI("JniDevicePropProvisioningStatus::onDevicePropProvisioningStatus - %d", esResult);
- if (!jDevicePropProvisioningStatus)
- {
- ES_LOGE("JniDevicePropProvisioningStatus::onDevicePropProvisioningStatus Unable to create the java object");
- return ;
- }
-
- env->CallVoidMethod(jListener, midL, jDevicePropProvisioningStatus);
-
- if (env->ExceptionCheck())
- {
- ES_LOGE("Java exception is thrown");
- checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
- return;
- }
-
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
-}
-
-void JniDevicePropProvisioningStatusListener::checkExAndRemoveListener(JNIEnv *env)
-{
- if (env->ExceptionCheck())
- {
- jthrowable ex = env->ExceptionOccurred();
- env->ExceptionClear();
- m_ownerResource->removeStatusListener<JniDevicePropProvisioningStatusListener>(env, m_jwListener);
- env->Throw((jthrowable)ex);
- }
- else
- {
- m_ownerResource->removeStatusListener<JniDevicePropProvisioningStatusListener>(env, m_jwListener);
- }
-}
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2016 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.
- *
- ******************************************************************/
-
-#ifndef __JNI_ES_DEVICE_PROP_PROVISIONING_STATUS_LISTENER_H_
-#define __JNI_ES_DEVICE_PROP_PROVISIONING_STATUS_LISTENER_H_
-
-#include <jni.h>
-
-#include "RemoteEnrollee.h"
-#include "ESRichCommon.h"
-
-#include "JniJvm.h"
-
-class JniRemoteEnrollee;
-
-using namespace OIC::Service;
-
-class JniDevicePropProvisioningStatusListener
-{
- public:
- /**
- * @brief constructor
- */
- JniDevicePropProvisioningStatusListener(JNIEnv *env, jobject jListener, JniRemoteEnrollee *resource);
-
- /**
- * @brief destructor
- */
- ~JniDevicePropProvisioningStatusListener();
-
- /**
- * @brief callback function that will be passed to Native layer
- */
- void onDevicePropProvisioningStatusCallback (std::shared_ptr<DevicePropProvisioningStatus> devicePropProvisioningStatus);
-
- private:
- jweak m_jwListener;
- JniRemoteEnrollee *m_ownerResource;
- void checkExAndRemoveListener(JNIEnv *env);
-};
-
-#endif //__JNI_ES_DEVICE_PROP_PROVISIONING_STATUS_LISTENER_H_
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2016 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 <memory>
-#include <vector>
-
-#include "OCPlatform.h"
-#include "OCResource.h"
-#include "octypes.h"
-#include "ESRichCommon.h"
-
-#include "JniOcResource.h"
-#include "JniEasySetup.h"
-
-using namespace OC;
-using namespace OIC::Service;
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-JNIEXPORT jobject JNICALL
-Java_org_iotivity_service_easysetup_mediator_EasySetup_nativeCreateRemoteEnrollee
-(JNIEnv *env, jobject thiz, jobject jResource)
-{
- ES_LOGI("JniEasySetup::nativeCreateRemoteEnrollee enter");
-
- std::shared_ptr<RemoteEnrollee> nativeRemoteEnrollee = NULL;
- jobject jRemoteEnrollee = NULL;
-
- if(!jResource)
- {
- ES_LOGE("JniEasySetup::nativeCreateRemoteEnrollee Invalid param.");
- return NULL;
- }
-
- JniOcResource* jniOcResource = JniOcResource::getJniOcResourcePtr(env, jResource);
-
- if (!jniOcResource)
- {
- ES_LOGE("JniEasySetup::nativeCreateRemoteEnrollee getJniOcResourcePtr returns nullptr.");
- return NULL;
- }
-
- try
- {
- nativeRemoteEnrollee = EasySetup::getInstance()->createRemoteEnrollee(jniOcResource->getOCResource());
- if (!nativeRemoteEnrollee)
- {
- ES_LOGE("Failed to create RemoteEnrollee object.");
- return NULL;
- }
-
- //create the java object
- jRemoteEnrollee = env->NewObject(g_cls_RemoteEnrollee, g_mid_RemoteEnrollee_ctor);
- if (!jRemoteEnrollee)
- {
- ES_LOGE("JniEasySetup::nativeCreateRemoteEnrollee Unable to create the java object");
- return NULL;
- }
- JniRemoteEnrollee *jniRemoteEnrollee = new JniRemoteEnrollee(nativeRemoteEnrollee);
- ESSetHandle<JniRemoteEnrollee>(env, jRemoteEnrollee, jniRemoteEnrollee);
- }
- catch (ESBadRequestException exception)
- {
- ES_LOGE("JniEasySetup::nativeCreateRemoteEnrollee Unable to create the Native EnrolleeDevice");
- //throw the exception to java layer
- throwESException( env, exception.what());
- }
-
- ES_LOGI("JniEasySetup::nativeCreateRemoteEnrollee exit");
-
- return jRemoteEnrollee;
-}
-#ifdef __cplusplus
-}
-#endif
-
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2016 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.
- *
- ******************************************************************/
-
-/** @file JniEasySetup.h
- *
- * @brief This file contains native API for creating RemoteEnrollee Device
- */
-
-#ifndef __JNI_ES_EASYSETUP_H
-#define __JNI_ES_EASYSETUP_H
-
-#include <jni.h>
-
-#include "EasySetup.hpp"
-#include "RemoteEnrollee.h"
-#include "ESException.h"
-#include "oic_string.h"
-
-#include "JniJvm.h"
-#include "JniEasySetup.h"
-#include "JniRemoteEnrollee.h"
-#include "JniEsUtils.h"
-
-using namespace OIC::Service;
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
- * API for creating and returning the RemoteEnrollee object to Java Layer
- *
- * @return jobject - RemoteEnrolleee
- */
-JNIEXPORT jobject JNICALL
-Java_org_iotivity_service_easysetup_mediator_EasySetup_nativeCreateRemoteEnrollee
-(JNIEnv *env, jobject thiz, jobject jResource);
-
-
-#ifdef __cplusplus
-}
-#endif
-#endif // __JNI_ES_EASYSETUP_H
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2016 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.
- *
- ******************************************************************/
-
-/** @file JniEsLisenerManager.h
- *
- * @brief This file contains JNI Listener Manager class for JniRemoteEnrollee
- */
-
-#ifndef __JNI_ES_LISTENER_MANAGER_H_
-#define __JNI_ES_LISTENER_MANAGER_H_
-
-#include <mutex>
-#include <map>
-
-class JniRemoteEnrollee;
-
-/**
- * @class JniEsListenerManager
- * @brief This class provides functions for managing listeners
- *
- */
-template <class T>
-class JniEsListenerManager
-{
- public:
- /**
- * API for Adding the Listener to listener Map.
- *
- * @param owner - JniRemoteEnrollee
- */
- T *addListener(JNIEnv *env, jobject jListener, JniRemoteEnrollee *owner)
- {
- T *onEventListener = NULL;
-
- m_mapMutex.lock();
-
- for (auto it = m_listenerMap.begin(); it != m_listenerMap.end(); ++it)
- {
- if (env->IsSameObject(jListener, it->first))
- {
- auto refPair = it->second;
- onEventListener = refPair.first;
- refPair.second++;
- it->second = refPair;
- m_listenerMap.insert(*it);
- ES_LOGD("OnEventListener: ref. count is incremented");
- break;
- }
- }
- if (!onEventListener)
- {
- onEventListener = new T(env, jListener, owner);
- jobject jgListener = env->NewGlobalRef(jListener);
-
- if (jgListener)
- {
- m_listenerMap.insert(
- std::pair < jobject,
- std::pair<T *, int >> (jgListener, std::pair<T *, int>(onEventListener, 1)));
- ES_LOGD("OnEventListener: new listener");
- }
- else
- {
- ES_LOGD("OnEventListener: Failed to create global listener ref.");
- delete onEventListener;
- onEventListener = NULL;
- }
- }
- m_mapMutex.unlock();
- return onEventListener;
- }
-
- /**
- * @brief API for removing the Listener from listener Map.
- */
- void removeListener(JNIEnv *env, jobject jListener)
- {
- m_mapMutex.lock();
- for (auto it = m_listenerMap.begin(); it != m_listenerMap.end(); ++it)
- {
- if (env->IsSameObject(jListener, it->first))
- {
- auto refPair = it->second;
- if (refPair.second > 1)
- {
- refPair.second--;
- it->second = refPair;
- m_listenerMap.insert(*it);
- ES_LOGI("OnEventListener: ref. count is decremented");
- }
- else
- {
- env->DeleteGlobalRef(it->first);
- T *listener = refPair.first;
- delete listener;
- m_listenerMap.erase(it);
-
- ES_LOGI("OnEventListener is removed");
- }
- break;
- }
- }
- m_mapMutex.unlock();
- }
-
- /**
- * @brief API for removing all the Listener from listener Map.
- */
- void removeAllListeners(JNIEnv *env)
- {
- m_mapMutex.lock();
-
- for (auto &pair : m_listenerMap)
- {
- env->DeleteGlobalRef(pair.first);
- auto refPair = pair.second;
- delete refPair.first;
- }
- m_listenerMap.clear();
-
- m_mapMutex.unlock();
- }
-
- private:
- std::map<jobject, std::pair<T *, int>> m_listenerMap;
- std::mutex m_mapMutex;
-};
-
-#endif //__JNI_ES_LISTENER_MANAGER_H_
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2016 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 "JniEsUtils.h"
-
-void throwESException(JNIEnv *env, std::string reason)
-{
- jobject ex = env->NewObject(g_cls_ESException, g_mid_ESException_ctor,
- env->NewStringUTF(reason.c_str()));
- if (!ex)
- {
- ES_LOGI("throwException : jobject is NULL");
- }
- env->Throw((jthrowable)ex);
-}
-
-OCConnectivityType getOCConnectivityTypeFromInt(int connectivityType)
-{
- switch (connectivityType)
- {
- case CT_DEFAULT:
- return CT_DEFAULT;
- case CT_ADAPTER_IP:
- return CT_ADAPTER_IP;
-
- //May be need to add more types, if easy setup service support more transport.
- }
- return CT_DEFAULT;
-}
-
-WIFI_AUTHTYPE getWifiAuthTypeFromInt(int authType)
-{
- switch (authType)
- {
- case 0:
- return WIFI_AUTHTYPE::NONE_AUTH;
- case 1:
- return WIFI_AUTHTYPE::WEP;
- case 2:
- return WIFI_AUTHTYPE::WPA_PSK;
- case 3:
- return WIFI_AUTHTYPE::WPA2_PSK;
- }
- return NONE_AUTH;
-}
-
-WIFI_ENCTYPE getWifiEncTypeFromInt(int encType)
-{
- switch (encType)
- {
- case 0:
- return WIFI_ENCTYPE::NONE_ENC;
- case 1:
- return WIFI_ENCTYPE::WEP_64;
- case 2:
- return WIFI_ENCTYPE::WEP_128;
- case 3:
- return WIFI_ENCTYPE::TKIP;
- case 4:
- return WIFI_ENCTYPE::AES;
- case 5:
- return WIFI_ENCTYPE::TKIP_AES;
- }
- return NONE_ENC;
-}
-
-int convertNativeWifiFreqToInt(WIFI_FREQ wifiFreq)
-{
- switch (wifiFreq)
- {
- case WIFI_FREQ::WIFI_24G:
- return 0;
- case WIFI_FREQ::WIFI_5G:
- return 1;
- case WIFI_FREQ::WIFI_BOTH:
- return 2;
- }
-}
-
-int convertNativeWifiModeToInt(WIFI_MODE wifiMode)
-{
- switch (wifiMode)
- {
- case WIFI_MODE::WIFI_11A:
- return 0;
- case WIFI_MODE::WIFI_11B:
- return 1;
- case WIFI_MODE::WIFI_11G:
- return 2;
- case WIFI_MODE::WIFI_11N:
- return 3;
- case WIFI_MODE::WIFI_11AC:
- return 4;
- }
-}
\ No newline at end of file
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2016 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.
- *
- ******************************************************************/
-
-/**
- * @file JniESUtils.h
- *
- * @brief This file contains the utility functions for JNI layer
- */
-
-#ifndef __JNI_ES_UTILS_H_
-#define __JNI_ES_UTILS_H_
-
-#include <jni.h>
-#include <string>
-
-#include "ESRichCommon.h"
-#include "octypes.h"
-
-#include "JniJvm.h"
-
-using namespace OIC::Service;
-
-/**
- * @brief Throw the Exception to the java layer
- */
-void throwESException(JNIEnv *env, std::string reason);
-
-/**
-* @brief Convert integer to OCconnectivity Enum
-*/
-OCConnectivityType getOCConnectivityTypeFromInt(int connectivityType);
-
-WIFI_AUTHTYPE getWifiAuthTypeFromInt(int authType);
-WIFI_ENCTYPE getWifiEncTypeFromInt(int encType);
-int convertNativeWifiFreqToInt(WIFI_FREQ wifiFreq);
-int convertNativeWifiModeToInt(WIFI_MODE wifiMode);
-#endif //__JNI_ES_UTILS_H_
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2016 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 "JniGetConfigurationStatusListener.h"
-#include "JniRemoteEnrollee.h"
-
-using namespace OC;
-using namespace OIC::Service;
-
-JniGetConfigurationStatusListener::JniGetConfigurationStatusListener(JNIEnv *env, jobject jListener,
- JniRemoteEnrollee *owner)
- : m_ownerResource(owner)
-{
- m_jwListener = env->NewWeakGlobalRef(jListener);
-}
-
-JniGetConfigurationStatusListener::~JniGetConfigurationStatusListener()
-{
- ES_LOGI("~JniGetConfigurationStatusListener()");
- if (m_jwListener)
- {
- jint ret;
- JNIEnv *env = GetESJNIEnv(ret);
- if (NULL == env) return;
- env->DeleteWeakGlobalRef(m_jwListener);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
- }
-}
-
-void JniGetConfigurationStatusListener::getConfigurationStatusCallback (
- std::shared_ptr<GetConfigurationStatus> getConfigurationStatusCb)
-{
- ES_LOGI("JniGetConfigurationStatusListener::provisioiningStatusCallback enter");
-
- jint ret;
- JNIEnv *env = GetESJNIEnv(ret);
- if (NULL == env) return;
- jobject jListener = env->NewLocalRef(m_jwListener);
- if (!jListener)
- {
- checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
- return;
- }
-
- jclass clsL = env->GetObjectClass(jListener);
- if (!clsL)
- {
- checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
- return;
- }
-
- jmethodID midL = env->GetMethodID(clsL, "onProgress",
- "(Lorg/iotivity/service/easysetup/mediator/"
- "GetConfigurationStatus;"
- ")V");
-
- if (!midL)
- {
- checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
- return;
- }
-
- EnrolleeConf enrolleeConf = getConfigurationStatusCb->getEnrolleeConf();
- OCRepresentation m_ProvRep = enrolleeConf.getEasySetupRep();
-
- OCRepresentation* rep = new OCRepresentation(m_ProvRep);
- jlong handle = reinterpret_cast<jlong>(rep);
- jobject jRepresentation = env->NewObject(g_cls_OcRepresentation, g_mid_OcRepresentation_N_ctor_bool,
- handle, true);
- if (!jRepresentation)
- {
- delete rep;
- checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret)
- {
- g_jvm->DetachCurrentThread();
- }
- return;
- }
-
- jobject jEnrolleeConf = NULL;
- jEnrolleeConf = env->NewObject(g_cls_EnrolleeConf, g_mid_EnrolleeConf_ctor, (jobject)jRepresentation);
- if (!jEnrolleeConf) {
- ES_LOGE("JniGetConfigurationStatusListener::getConfigurationStatusCallback Unable to create the jEnrolleeConf");
- return ;
- }
-
- ESResult esResult = getConfigurationStatusCb->getESResult();
- jobject jgetConfigurationStatus = NULL;
- jgetConfigurationStatus = env->NewObject(g_cls_getConfigurationStatus,
- g_mid_getConfigurationStatus_ctor,
- (jint)esResult,
- (jobject)jEnrolleeConf);
-
- if (!jgetConfigurationStatus)
- {
- ES_LOGE("JniGetConfigurationStatusListener::getConfigurationStatusCallback Unable to create the java object");
- return ;
- }
-
- env->CallVoidMethod(jListener, midL, jgetConfigurationStatus);
-
- if (env->ExceptionCheck())
- {
- ES_LOGE("Java exception is thrown");
- checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
- return;
- }
-
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
-}
-
-void JniGetConfigurationStatusListener::checkExAndRemoveListener(JNIEnv *env)
-{
- if (env->ExceptionCheck())
- {
- jthrowable ex = env->ExceptionOccurred();
- env->ExceptionClear();
- m_ownerResource->removeStatusListener<JniGetConfigurationStatusListener>(env, m_jwListener);
-
- env->Throw((jthrowable)ex);
- }
- else
- {
- m_ownerResource->removeStatusListener<JniGetConfigurationStatusListener>(env, m_jwListener);
- }
-}
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2016 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.
- *
- ******************************************************************/
-
-#ifndef __JNI_ES_GET_CONFIGURATION_STATUS_LISTENER_H_
-#define __JNI_ES_GET_CONFIGURATION_STATUS_LISTENER_H_
-
-#include <jni.h>
-
-#include "OCPlatform.h"
-#include "RemoteEnrollee.h"
-#include "ESRichCommon.h"
-
-#include "JniJvm.h"
-
-class JniRemoteEnrollee;
-
-using namespace OIC::Service;
-
-class JniGetConfigurationStatusListener
-{
- public:
- /**
- * @brief constructor
- */
- JniGetConfigurationStatusListener(JNIEnv *env, jobject jListener, JniRemoteEnrollee *resource);
-
- /**
- * @brief destructor
- */
- ~JniGetConfigurationStatusListener();
-
- /**
- * @brief callback function that will be passed to Native layer
- */
- void getConfigurationStatusCallback (std::shared_ptr<GetConfigurationStatus> getConfigurationStatus);
-
- private:
- jweak m_jwListener;
- JniRemoteEnrollee *m_ownerResource;
- void checkExAndRemoveListener(JNIEnv *env);
-};
-
-#endif //__JNI_ES_GET_CONFIGURATION_STATUS_LISTENER_H_
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2016 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 "JniGetEnrolleeStatusListener.h"
-#include "JniRemoteEnrollee.h"
-
-using namespace OC;
-using namespace OIC::Service;
-
-JniGetEnrolleeStatusListener::JniGetEnrolleeStatusListener(JNIEnv *env, jobject jListener,
- JniRemoteEnrollee *owner)
- : m_ownerResource(owner)
-{
- m_jwListener = env->NewWeakGlobalRef(jListener);
-}
-
-JniGetEnrolleeStatusListener::~JniGetEnrolleeStatusListener()
-{
- ES_LOGI("~JniGetEnrolleeStatusListener()");
- if (m_jwListener)
- {
- jint ret;
- JNIEnv *env = GetESJNIEnv(ret);
- if (NULL == env) return;
- env->DeleteWeakGlobalRef(m_jwListener);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
- }
-}
-
-void JniGetEnrolleeStatusListener::getEnrolleeStatusCallback (
- std::shared_ptr<GetEnrolleeStatus> getEnrolleeStatusCb)
-{
- ES_LOGI("JniGetEnrolleeStatusListener::getEnrolleeStatusCallback enter");
-
- jint ret;
- JNIEnv *env = GetESJNIEnv(ret);
- if (NULL == env) return;
- jobject jListener = env->NewLocalRef(m_jwListener);
- if (!jListener)
- {
- checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
- return;
- }
-
- jclass clsL = env->GetObjectClass(jListener);
- if (!clsL)
- {
- checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
- return;
- }
-
- jmethodID midL = env->GetMethodID(clsL, "onProgress",
- "(Lorg/iotivity/service/easysetup/mediator/"
- "GetEnrolleeStatus;"
- ")V");
-
- if (!midL)
- {
- checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
- return;
- }
-
- EnrolleeStatus enrolleeStatus = getEnrolleeStatusCb->getEnrolleeStatus();
- OCRepresentation m_Rep = enrolleeStatus.getRepresentation();
- OCRepresentation* rep = new OCRepresentation(m_Rep);
- jlong handle = reinterpret_cast<jlong>(rep);
- jobject jRepresentation = env->NewObject(g_cls_OcRepresentation,
- g_mid_OcRepresentation_N_ctor_bool,
- handle, true);
- if (!jRepresentation)
- {
- delete rep;
- checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret)
- {
- g_jvm->DetachCurrentThread();
- }
- return;
- }
-
- jobject jEnrolleeStatus = NULL;
- jEnrolleeStatus = env->NewObject(g_cls_EnrolleeStatus,
- g_mid_EnrolleeStatus_ctor,
- (jobject)jRepresentation);
- if (!jEnrolleeStatus) {
- ES_LOGE("JniGetEnrolleeStatusListener::getEnrolleeStatusCallback Unable to create the jEnrolleeStatus");
- return ;
- }
-
- ESResult esResult = getEnrolleeStatusCb->getESResult();
- jobject jgetEnrolleeStatus = NULL;
- jgetEnrolleeStatus = env->NewObject(g_cls_getEnrolleeStatus,
- g_mid_getEnrolleeStatus_ctor,
- (jint)esResult,
- (jobject)jEnrolleeStatus);
-
- if (!jgetEnrolleeStatus)
- {
- ES_LOGE("JniGetEnrolleeStatusListener::getEnrolleeStatusCallback Unable to create the java object");
- return ;
- }
-
- env->CallVoidMethod(jListener, midL, jgetEnrolleeStatus);
-
- if (env->ExceptionCheck())
- {
- ES_LOGE("Java exception is thrown");
- checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
- return;
- }
-
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
-}
-
-void JniGetEnrolleeStatusListener::checkExAndRemoveListener(JNIEnv *env)
-{
- if (env->ExceptionCheck())
- {
- jthrowable ex = env->ExceptionOccurred();
- env->ExceptionClear();
- m_ownerResource->removeStatusListener<JniGetEnrolleeStatusListener>
- (env, m_jwListener);
-
- env->Throw((jthrowable)ex);
- }
- else
- {
- m_ownerResource->removeStatusListener<JniGetEnrolleeStatusListener>
- (env, m_jwListener);
- }
-}
-
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2016 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.
- *
- ******************************************************************/
-
-#ifndef __JNI_ES_GET_ENROLLEE_STATUS_LISTENER_H_
-#define __JNI_ES_GET_ENROLLEE_STATUS_LISTENER_H_
-
-#include <jni.h>
-
-#include "OCPlatform.h"
-#include "RemoteEnrollee.h"
-#include "ESRichCommon.h"
-
-#include "JniJvm.h"
-
-class JniRemoteEnrollee;
-
-using namespace OIC::Service;
-
-class JniGetEnrolleeStatusListener
-{
- public:
- /**
- * @brief constructor
- */
- JniGetEnrolleeStatusListener(JNIEnv *env, jobject jListener, JniRemoteEnrollee *resource);
-
- /**
- * @brief destructor
- */
- ~JniGetEnrolleeStatusListener();
-
- /**
- * @brief callback function that will be passed to Native layer
- */
- void getEnrolleeStatusCallback (std::shared_ptr<GetEnrolleeStatus> getEnrolleeStatus);
-
- private:
- jweak m_jwListener;
- JniRemoteEnrollee *m_ownerResource;
- void checkExAndRemoveListener(JNIEnv *env);
-};
-
-#endif //__JNI_ES_GET_CONFIGURATION_STATUS_LISTENER_H_
-
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2016 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 "JniJvm.h"
-
-JavaVM *g_jvm = NULL;
-
-jclass g_cls_RemoteEnrollee = NULL;
-jclass g_cls_ESException = NULL;
-jclass g_cls_EnrolleeStatus = NULL;
-jclass g_cls_EnrolleeConf = NULL;
-jclass g_cls_getEnrolleeStatus = NULL;
-jclass g_cls_getConfigurationStatus = NULL;
-jclass g_cls_SecurityProvisioningStatus = NULL;
-jclass g_cls_DevicePropProvisioningStatus = NULL;
-jclass g_cls_CloudPropProvisioningStatus = NULL;
-jclass g_cls_Integer = NULL;
-jclass g_cls_OcRepresentation = NULL;
-
-jmethodID g_mid_RemoteEnrollee_ctor = NULL;
-jmethodID g_mid_ESException_ctor = NULL;
-jmethodID g_mid_EnrolleeStatus_ctor = NULL;
-jmethodID g_mid_EnrolleeConf_ctor = NULL;
-jmethodID g_mid_getEnrolleeStatus_ctor = NULL;
-jmethodID g_mid_getConfigurationStatus_ctor = NULL;
-jmethodID g_mid_SecurityProvisioningStatus_ctor = NULL;
-jmethodID g_mid_DevicePropProvisioningStatus_ctor = NULL;
-jmethodID g_mid_CloudPropProvisioningStatus_ctor = NULL;
-jmethodID g_mid_Integer_ctor = NULL;
-jmethodID g_mid_OcRepresentation_N_ctor_bool = NULL;
-
-// JNI OnLoad
-JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved)
-{
- ES_LOGI("JNI_OnLoad");
- JNIEnv *env;
- g_jvm = vm;
-
- if (g_jvm->GetEnv((void **)&env, JNI_CURRENT_VERSION) != JNI_OK)
- {
- ES_LOGE("Failed to get the environment using GetEnv()");
- return JNI_ERR;
- }
-
- jclass clazz = nullptr;
-
- // Remote Enrollee
- clazz = env->FindClass("org/iotivity/service/easysetup/mediator/RemoteEnrollee");
- if (!clazz) return JNI_ERR;
- g_cls_RemoteEnrollee = (jclass)env->NewGlobalRef(clazz);
- env->DeleteLocalRef(clazz);
-
- g_mid_RemoteEnrollee_ctor = env->GetMethodID(g_cls_RemoteEnrollee, "<init>",
- "(J)V");
- if (!g_mid_RemoteEnrollee_ctor) return JNI_ERR;
-
- // ESException
- clazz = env->FindClass("org/iotivity/service/easysetup/mediator/ESException");
- if (!clazz) return JNI_ERR;
- g_cls_ESException = (jclass)env->NewGlobalRef(clazz);
- env->DeleteLocalRef(clazz);
-
- g_mid_ESException_ctor = env->GetMethodID(g_cls_ESException, "<init>", "(Ljava/lang/String;)V");
- if (!g_mid_ESException_ctor) return JNI_ERR;
-
- // EnrolleeStatus
- clazz = env->FindClass("org/iotivity/service/easysetup/mediator/EnrolleeStatus");
- if (!clazz) return JNI_ERR;
-
- g_cls_EnrolleeStatus = (jclass)env->NewGlobalRef(clazz);
- env->DeleteLocalRef(clazz);
-
- g_mid_EnrolleeStatus_ctor = env->GetMethodID(g_cls_EnrolleeStatus, "<init>",
- "(Lorg/iotivity/base/OcRepresentation;)V");
- if (!g_mid_EnrolleeStatus_ctor) return JNI_ERR;
-
- // EnrolleeConf
- clazz = env->FindClass("org/iotivity/service/easysetup/mediator/EnrolleeConf");
- if (!clazz) return JNI_ERR;
-
- g_cls_EnrolleeConf = (jclass)env->NewGlobalRef(clazz);
- env->DeleteLocalRef(clazz);
-
- g_mid_EnrolleeConf_ctor = env->GetMethodID(g_cls_EnrolleeConf, "<init>",
- "(Lorg/iotivity/base/OcRepresentation;)V");
- if (!g_mid_EnrolleeConf_ctor) return JNI_ERR;
-
- // getEnrolleeStatus
- clazz = env->FindClass("org/iotivity/service/easysetup/mediator/GetEnrolleeStatus");
- if (!clazz) return JNI_ERR;
-
- g_cls_getEnrolleeStatus = (jclass)env->NewGlobalRef(clazz);
- env->DeleteLocalRef(clazz);
-
- g_mid_getEnrolleeStatus_ctor = env->GetMethodID(g_cls_getEnrolleeStatus, "<init>",
- "(ILorg/iotivity/service/easysetup/mediator/EnrolleeStatus;)V");
- if (!g_mid_getEnrolleeStatus_ctor) return JNI_ERR;
-
- // getConfigurationStatus
- clazz = env->FindClass("org/iotivity/service/easysetup/mediator/GetConfigurationStatus");
- if (!clazz) return JNI_ERR;
-
- g_cls_getConfigurationStatus = (jclass)env->NewGlobalRef(clazz);
- env->DeleteLocalRef(clazz);
-
- g_mid_getConfigurationStatus_ctor = env->GetMethodID(g_cls_getConfigurationStatus, "<init>",
- "(ILorg/iotivity/service/easysetup/mediator/EnrolleeConf;)V");
- if (!g_mid_getConfigurationStatus_ctor) return JNI_ERR;
-
- // SecurityProvisioningStatus
- clazz = env->FindClass("org/iotivity/service/easysetup/mediator/SecurityProvisioningStatus");
- if (!clazz) return JNI_ERR;
-
- g_cls_SecurityProvisioningStatus = (jclass)env->NewGlobalRef(clazz);
- env->DeleteLocalRef(clazz);
-
- g_mid_SecurityProvisioningStatus_ctor = env->GetMethodID(g_cls_SecurityProvisioningStatus, "<init>",
- "(ILjava/lang/String;)V");
- if (!g_mid_SecurityProvisioningStatus_ctor) return JNI_ERR;
-
- // DevicePropProvisioningStatus
- clazz = env->FindClass("org/iotivity/service/easysetup/mediator/DevicePropProvisioningStatus");
- if (!clazz) return JNI_ERR;
-
- g_cls_DevicePropProvisioningStatus = (jclass)env->NewGlobalRef(clazz);
- env->DeleteLocalRef(clazz);
-
- g_mid_DevicePropProvisioningStatus_ctor = env->GetMethodID(g_cls_DevicePropProvisioningStatus, "<init>",
- "(I)V");
- if (!g_mid_DevicePropProvisioningStatus_ctor) return JNI_ERR;
-
- // CloudPropProvisioningStatus
- clazz = env->FindClass("org/iotivity/service/easysetup/mediator/CloudPropProvisioningStatus");
- if (!clazz) return JNI_ERR;
- g_cls_CloudPropProvisioningStatus = (jclass)env->NewGlobalRef(clazz);
- env->DeleteLocalRef(clazz);
-
- g_mid_CloudPropProvisioningStatus_ctor = env->GetMethodID(g_cls_CloudPropProvisioningStatus, "<init>",
- "(I)V");
- if (!g_mid_CloudPropProvisioningStatus_ctor) return JNI_ERR;
-
- // Integer
- clazz = env->FindClass("java/lang/Integer");
- if (!clazz) return JNI_ERR;
- g_cls_Integer = (jclass)env->NewGlobalRef(clazz);
- env->DeleteLocalRef(clazz);
-
- g_mid_Integer_ctor = env->GetMethodID(g_cls_Integer, "<init>",
- "(I)V");
- if (!g_mid_Integer_ctor) return JNI_ERR;
-
- //OcRepresentation
- clazz = env->FindClass("org/iotivity/base/OcRepresentation");
- if (!clazz) return JNI_ERR;
- g_cls_OcRepresentation = (jclass)env->NewGlobalRef(clazz);
- env->DeleteLocalRef(clazz);
-
- g_mid_OcRepresentation_N_ctor_bool = env->GetMethodID(g_cls_OcRepresentation, "<init>", "(JZ)V");
- if (!g_mid_OcRepresentation_N_ctor_bool) return JNI_ERR;
-
- return JNI_CURRENT_VERSION;
-}
-
-//JNI OnUnload
-JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *vm, void *reserved)
-{
- ES_LOGI("JNI_OnUnload");
- JNIEnv *env;
-
- if (g_jvm->GetEnv((void **)&env, JNI_CURRENT_VERSION) != JNI_OK)
- {
- ES_LOGE("Failed to get the environment using GetEnv()");
- return;
- }
- env->DeleteGlobalRef(g_cls_RemoteEnrollee);
- env->DeleteGlobalRef(g_cls_ESException);
-}
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2016 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.
- *
- ******************************************************************/
-
-/**
- * @file JniJvm.h
- *
- * @brief This file contains the essential declarations and functions required
- * for JNI implementation
- */
-
-#ifndef __JNI_ES_JVM_H
-#define __JNI_ES_JVM_H
-
-#include <jni.h>
-#include <string>
-#include <android/log.h>
-
-#define ESTAG "ES-JNI"
-#define JNI_CURRENT_VERSION JNI_VERSION_1_6
-
-#define ES_LOGI(...) __android_log_print(ANDROID_LOG_INFO, ESTAG, __VA_ARGS__)
-#define ES_LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, ESTAG, __VA_ARGS__)
-#define ES_LOGE(...) __android_log_print(ANDROID_LOG_ERROR, ESTAG, __VA_ARGS__)
-
-extern JavaVM *g_jvm;
-
-extern jclass g_cls_RemoteEnrollee;
-extern jclass g_cls_ESException;
-extern jclass g_cls_EnrolleeStatus;
-extern jclass g_cls_EnrolleeConf;
-extern jclass g_cls_getEnrolleeStatus;
-extern jclass g_cls_getConfigurationStatus;
-extern jclass g_cls_SecurityProvisioningStatus;
-extern jclass g_cls_DevicePropProvisioningStatus;
-extern jclass g_cls_CloudPropProvisioningStatus;
-extern jclass g_cls_Integer;
-extern jclass g_cls_OcRepresentation;
-
-extern jmethodID g_mid_RemoteEnrollee_ctor;
-extern jmethodID g_mid_ESException_ctor;
-extern jmethodID g_mid_EnrolleeStatus_ctor;
-extern jmethodID g_mid_EnrolleeConf_ctor;
-extern jmethodID g_mid_getEnrolleeStatus_ctor;
-extern jmethodID g_mid_getConfigurationStatus_ctor;
-extern jmethodID g_mid_SecurityProvisioningStatus_ctor;
-extern jmethodID g_mid_DevicePropProvisioningStatus_ctor;
-extern jmethodID g_mid_CloudPropProvisioningStatus_ctor;
-extern jmethodID g_mid_Integer_ctor;
-extern jmethodID g_mid_OcRepresentation_N_ctor_bool;
-
-typedef void(*RemoveListenerCallback)(JNIEnv *env, jobject jListener);
-
-/**
- * @brief Get the native handle field
- */
-static jfieldID ESGetHandleField(JNIEnv *env, jobject jobj)
-{
- jclass cls = env->GetObjectClass(jobj);
- return env->GetFieldID(cls, "m_nativeHandle", "J");
-}
-
-/**
- * @brief Get the native handle
- */
-template <typename T>
-static T *ESGetHandle(JNIEnv *env, jobject jobj)
-{
- jlong handle = env->GetLongField(jobj, ESGetHandleField(env, jobj));
- return reinterpret_cast<T *>(handle);
-}
-
-/**
- * @brief Set the native handle
- */
-template <typename T>
-static void ESSetHandle(JNIEnv *env, jobject jobj, T *type)
-{
- jlong handle = reinterpret_cast<jlong>(type);
-
- env->SetLongField(jobj, ESGetHandleField(env, jobj), handle);
-}
-
-/**
- * @brief Get the JNI Environment
- */
-static JNIEnv *GetESJNIEnv(jint &ret)
-{
- JNIEnv *env = NULL;
-
- ret = g_jvm->GetEnv((void **)&env, JNI_CURRENT_VERSION);
- switch (ret)
- {
- case JNI_OK:
- return env;
- case JNI_EDETACHED:
- if (g_jvm->AttachCurrentThread(&env, NULL) < 0)
- {
- ES_LOGE("Failed to get the environment");
- return nullptr;
- }
- else
- {
- return env;
- }
-
- case JNI_EVERSION:
- ES_LOGE("JNI version not supported");
- default:
- ES_LOGE("Failed to get the environment");
- return nullptr;
- }
-}
-#endif // __JNI_ES_JVM_H
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2016 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 "JniRemoteEnrollee.h"
-
-#include "JniOcRepresentation.h"
-
-using namespace OIC::Service;
-
-JniRemoteEnrollee::JniRemoteEnrollee(std::shared_ptr<RemoteEnrollee> remoteEnrollee)
- : m_sharedResource(remoteEnrollee) {}
-
-JniRemoteEnrollee::~JniRemoteEnrollee()
-{
- ES_LOGD("JniRemoteEnrollee::~JniRemoteEnrollee()");
- m_sharedResource = NULL;
-
- jint envRet;
- JNIEnv *env = GetESJNIEnv(envRet);
- if (NULL == env) return;
-
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
-}
-
-JniRemoteEnrollee *JniRemoteEnrollee::getJniRemoteEnrollee(JNIEnv *env, jobject thiz)
-{
- JniRemoteEnrollee *remoteEnrollee = ESGetHandle<JniRemoteEnrollee>(env, thiz);
- if (env->ExceptionCheck())
- {
- ES_LOGE("getJniRemoteEnrollee :: Failed to get native handle from RemoteEnrollee object");
- }
- if (!remoteEnrollee)
- {
- ES_LOGE("getJniRemoteEnrollee :: no resource");
- }
- return remoteEnrollee;
-}
-
-void JniRemoteEnrollee::getStatus(JNIEnv *env, jobject jListener)
-{
- JniGetEnrolleeStatusListener *onGetEnrolleeStatusReceived =
- addStatusListener<JniGetEnrolleeStatusListener>(env, jListener);
-
- GetStatusCb getEnrolleeStatusCallback = [onGetEnrolleeStatusReceived]
- (std::shared_ptr<OIC::Service::GetEnrolleeStatus > getEnrolleeStatus)
- {
- onGetEnrolleeStatusReceived->getEnrolleeStatusCallback(getEnrolleeStatus);
- };
-
- try
- {
- m_sharedResource->getStatus(getEnrolleeStatusCallback);
- }
- catch (ESBadRequestException exception)
- {
- ES_LOGE("JNI getStatus :: Exception occured");
- //throw the exception to java
- throwESException( env, exception.what());
- }
-}
-
-void JniRemoteEnrollee::getConfiguration(JNIEnv *env, jobject jListener)
-{
- JniGetConfigurationStatusListener *onGetConfigurationStatusReceived =
- addStatusListener<JniGetConfigurationStatusListener>(env, jListener);
-
- GetConfigurationStatusCb getConfigurationStatusCallback = [onGetConfigurationStatusReceived]
- (std::shared_ptr<OIC::Service::GetConfigurationStatus > getConfigurationStatus)
- {
- onGetConfigurationStatusReceived->getConfigurationStatusCallback(getConfigurationStatus);
- };
-
- try
- {
- m_sharedResource->getConfiguration(getConfigurationStatusCallback);
- }
- catch (ESBadRequestException exception)
- {
- ES_LOGE("JNI getConfiguration :: Exception occured");
- //throw the exception to java
- throwESException( env, exception.what());
- }
-}
-
-void JniRemoteEnrollee::provisionSecurity(JNIEnv *env, jobject jListener)
-{
- JniSecurityStatusListener *onSecurityProvStatusReceived =
- addStatusListener<JniSecurityStatusListener>(env, jListener);
-
- SecurityProvStatusCb secProvStatusCallback = [onSecurityProvStatusReceived]
- (std::shared_ptr<OIC::Service::SecProvisioningStatus > SecProvisioningStatus)
- {
- onSecurityProvStatusReceived->secProvisionStatusCallback(SecProvisioningStatus);
- };
-
- try
- {
- m_sharedResource->provisionSecurity(secProvStatusCallback);
- }
- catch (ESBadRequestException exception)
- {
- ES_LOGE("JNI provisionSecurity :: Exception occured");
- //throw the exception to java
- throwESException( env, exception.what());
- }
-}
-
-void JniRemoteEnrollee::provisionDeviceProperties(JNIEnv *env,
- jobject jRepresentation,
- jobject jListener)
-{
- OCRepresentation *representation = JniOcRepresentation::getOCRepresentationPtr(env, jRepresentation);
- if (!representation)
- {
- return;
- }
-
- DeviceProp deviceProp(*representation);
- JniDevicePropProvisioningStatusListener *onDevicePropProvStatusReceived =
- addStatusListener<JniDevicePropProvisioningStatusListener>(env, jListener);
-
- DevicePropProvStatusCb devicePropProvStatusCallback = [onDevicePropProvStatusReceived]
- (std::shared_ptr<OIC::Service::DevicePropProvisioningStatus > devicePropProvisioningStatus)
- {
- onDevicePropProvStatusReceived->onDevicePropProvisioningStatusCallback(devicePropProvisioningStatus);
- };
-
- try
- {
- m_sharedResource->provisionDeviceProperties(deviceProp, devicePropProvStatusCallback);
- }
- catch (ESBadRequestException exception)
- {
- ES_LOGE("JNI provisionDeviceProperties :: Exception occured");
- //throw the exception to java
- throwESException( env, exception.what());
- }
-}
-
-void JniRemoteEnrollee::provisionCloudProperties(JNIEnv *env,
- jobject jRepresentation,
- jstring jCloudID,
- jint jCredID,
- jobject jListener)
-{
- OCRepresentation *representation = JniOcRepresentation::getOCRepresentationPtr(env, jRepresentation);
- if (!representation)
- {
- return;
- }
- if (!jCloudID)
- {
- return;
- }
-
- CloudProp cloudProp(*representation);
- cloudProp.setCloudID(env->GetStringUTFChars(jCloudID, NULL));
- cloudProp.setCredID(jCredID);
-
- JniCloudPropProvisioningStatusListener *onCloudPropProvisioningStatusReceived =
- addStatusListener<JniCloudPropProvisioningStatusListener>(env, jListener);
-
- CloudPropProvStatusCb cloudPropProvStatusCallback = [onCloudPropProvisioningStatusReceived]
- (std::shared_ptr< OIC::Service::CloudPropProvisioningStatus > cloudPropProvisioningStatus)
-
- {
- onCloudPropProvisioningStatusReceived->onCloudPropProvisioningStatus(cloudPropProvisioningStatus);
- };
-
- try
- {
- m_sharedResource->provisionCloudProperties(cloudProp, cloudPropProvStatusCallback);
- }
- catch (ESBadRequestException exception)
- {
- ES_LOGE("JNI startProvisioning :: Exception occured");
- //throw the exception to java
- throwESException(env, exception.what());
- }
-}
-
-//JNI
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_easysetup_mediator_RemoteEnrollee_nativeGetStatus
-(JNIEnv *env, jobject jClass, jobject jListener)
-{
- ES_LOGD("nativeGetStatus Enter");
-
- JniRemoteEnrollee *remoteEnrollee = JniRemoteEnrollee::getJniRemoteEnrollee(env, jClass);
- remoteEnrollee->getStatus(env, jListener);
-
- ES_LOGD("nativeGetStatus Exit");
-}
-
-//JNI
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_easysetup_mediator_RemoteEnrollee_nativeGetConfiguration
-(JNIEnv *env, jobject jClass, jobject jListener)
-{
- ES_LOGD("nativegetConfiguration Enter");
-
- JniRemoteEnrollee *remoteEnrollee = JniRemoteEnrollee::getJniRemoteEnrollee(env, jClass);
- remoteEnrollee->getConfiguration(env, jListener);
-
- ES_LOGD("nativegetConfiguration Exit");
-}
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_easysetup_mediator_RemoteEnrollee_nativeProvisionSecurity
-(JNIEnv *env, jobject jClass, jobject jListener)
-{
- ES_LOGD("nativeStartSecurityProvision Enter");
-
- JniRemoteEnrollee *remoteEnrollee = JniRemoteEnrollee::getJniRemoteEnrollee(env, jClass);
- remoteEnrollee->provisionSecurity(env, jListener);
-
- ES_LOGD("nativeStartSecurityProvision Exit");
-}
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_easysetup_mediator_RemoteEnrollee_nativeProvisionDeviceProperties
-(JNIEnv *env, jobject jClass, jobject jRepresentation, jobject jListener)
-{
- ES_LOGD("nativeProvisionDeviceProperties Enter");
-
- JniRemoteEnrollee *remoteEnrollee = JniRemoteEnrollee::getJniRemoteEnrollee(env, jClass);
- remoteEnrollee->provisionDeviceProperties(env, jRepresentation, jListener);
-
- ES_LOGD("nativeProvisionDeviceProperties Exit");
-}
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_easysetup_mediator_RemoteEnrollee_nativeProvisionCloudProperties
-(JNIEnv *env, jobject jClass, jobject jRepresentation, jstring jCloudID, jint jCredID, jobject jListener)
-{
- ES_LOGD("nativeprovisionCloudProperties Enter");
-
- JniRemoteEnrollee *remoteEnrollee = JniRemoteEnrollee::getJniRemoteEnrollee(env, jClass);
- remoteEnrollee->provisionCloudProperties(env, jRepresentation, jCloudID, jCredID, jListener);
-
- ES_LOGD("nativeprovisionCloudProperties Exit");
-}
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2016 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.
- *
- ******************************************************************/
-
-/** @file JniRemoteEnrollee.h
- *
- * @brief This file contains the JniRemoteEnrollee class
- * & declaration of RemoteEnrollee APIs for JNI implementation
- */
-
-#ifndef __JNI_ES_REMOTEENROLLEE_H
-#define __JNI_ES_REMOTEENROLLEE_H
-
-#include "ESRichCommon.h"
-#include "ESException.h"
-#include "RemoteEnrollee.h"
-
-#include "JniJvm.h"
-#include "JniEsUtils.h"
-#include "JniGetEnrolleeStatusListener.h"
-#include "JniGetConfigurationStatusListener.h"
-#include "JniSecurityStatusListener.h"
-#include "JniDevicePropProvisioningStatusListener.h"
-#include "JniCloudPropProvisioningStatusListener.h"
-#include "JniEsListenerManager.h"
-
-using namespace OIC::Service;
-
-/**
- * @class JniRemoteEnrollee
- * @brief This class contains all the APIs for RemoteEnrollee
- *
- * NOTE: JNI APIs internally call the APIs of this class.
- */
-class JniRemoteEnrollee
-{
- public:
-
- /**
- *@brief constructor
- */
- JniRemoteEnrollee(std::shared_ptr< RemoteEnrollee> remoteEnrollee);
-
- /**
- *@brief destructor
- */
- ~JniRemoteEnrollee();
-
- // ***** JNI APIs internally call the APIs of this class ***** //
- void getStatus(JNIEnv *env, jobject jListener);
- void getConfiguration(JNIEnv *env, jobject jListener);
- void provisionSecurity(JNIEnv *env, jobject jListener);
- void provisionDeviceProperties(JNIEnv *env, jobject jRepresentation, jobject jListener);
- void provisionCloudProperties(JNIEnv *env, jobject jRepresentation,
- jstring jCloudID,
- jint jCredID,
- jobject jListener);
-
- static JniRemoteEnrollee *getJniRemoteEnrollee(JNIEnv *env, jobject thiz);
-
- template <class T>
- T *addStatusListener(JNIEnv *env, jobject jListener)
- {
- return JniEsListenerManager<T>().addListener(env, jListener, this);
- };
-
- template <class T>
- void removeStatusListener(JNIEnv *env, jobject jListener)
- {
- JniEsListenerManager<T>().removeListener(env, jListener);
- };
-
- private:
- std::shared_ptr<RemoteEnrollee> m_sharedResource;
-
-};
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
- * API for starting the Request Enrollee status process.
- */
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_easysetup_mediator_RemoteEnrollee_nativeGetStatus
-(JNIEnv *env, jobject jClass, jobject jListener);
-
-/**
- * API for starting the Request EnrolleeConf process.
- */
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_easysetup_mediator_RemoteEnrollee_nativeGetConfiguration
-(JNIEnv *env, jobject jClass, jobject jListener);
-
-/**
- * API for starting the Sequrity provisioning process.
- */
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_easysetup_mediator_RemoteEnrollee_nativeProvisionSecurity
-(JNIEnv *env, jobject jClass, jobject jListener);
-
-/**
- * API for starting the Data provisioning process.
- */
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_easysetup_mediator_RemoteEnrollee_nativeProvisionDeviceProperties
-(JNIEnv *env, jobject jClass, jobject jRepresentation, jobject jListener);
-
-/**
- * API for starting the cloud provisioning process.
- */
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_easysetup_mediator_RemoteEnrollee_nativeProvisionCloudProperties
-(JNIEnv *env, jobject jClass, jobject jRepresentation, jstring jCloudID, jint jCredID, jobject jListener);
-
-#ifdef __cplusplus
-}
-#endif
-#endif // __JNI_ES_REMOTEENROLLEE_H
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2016 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 "JniSecurityStatusListener.h"
-#include "JniRemoteEnrollee.h"
-#include "oic_malloc.h"
-#include "oic_string.h"
-
-using namespace OIC::Service;
-
-JniSecurityStatusListener::JniSecurityStatusListener(JNIEnv *env, jobject jListener,
- JniRemoteEnrollee *owner)
- : m_ownerResource(owner)
-{
- m_jwListener = env->NewWeakGlobalRef(jListener);
-}
-
-JniSecurityStatusListener::~JniSecurityStatusListener()
-{
- ES_LOGI("~JniSecurityStatusListener()");
- if (m_jwListener)
- {
- jint ret;
- JNIEnv *env = GetESJNIEnv(ret);
- if (NULL == env) return;
- env->DeleteWeakGlobalRef(m_jwListener);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
- }
-}
-void JniSecurityStatusListener::secProvisionStatusCallback(
- std::shared_ptr<SecProvisioningStatus> secProvisioningStatus)
-{
-
- ES_LOGI("JniSecurityStatusListener::secProvisionStatusCallback enter");
-
- jint ret;
- JNIEnv *env = GetESJNIEnv(ret);
- if (NULL == env) return;
- jobject jListener = env->NewLocalRef(m_jwListener);
- if (!jListener)
- {
- checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
- return;
- }
-
- jclass clsL = env->GetObjectClass(jListener);
- if (!clsL)
- {
- checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
- return;
- }
-
- jmethodID midL = env->GetMethodID(clsL, "onProgress",
- "(Lorg/iotivity/service/easysetup/mediator/"
- "SecurityProvisioningStatus;"
- ")V");
-
- if (!midL)
- {
- checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
- return;
- }
-
- ESResult esResult = secProvisioningStatus->getESResult();
-
- //create the java object
- jobject jSecurityProvisioningStatus = NULL;
- jSecurityProvisioningStatus = env->NewObject(g_cls_SecurityProvisioningStatus,
- g_mid_SecurityProvisioningStatus_ctor,
- (jint)esResult,
- env->NewStringUTF(secProvisioningStatus->getDeviceUUID().c_str()));
-
- ES_LOGE("JniSecurityStatusListener::onSecurityProvisioningStatus UUID : %s",
- secProvisioningStatus->getDeviceUUID().c_str());
-
- if (!jSecurityProvisioningStatus)
- {
- ES_LOGE("JniSecurityStatusListener::onSecurityProvisioningStatus Unable to create the java object");
- return ;
- }
-
- env->CallVoidMethod(jListener, midL, jSecurityProvisioningStatus);
-
- if (env->ExceptionCheck())
- {
- ES_LOGE("Java exception is thrown");
- checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
- return;
- }
-
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
-}
-
-void JniSecurityStatusListener::checkExAndRemoveListener(JNIEnv *env)
-{
- if (env->ExceptionCheck())
- {
- jthrowable ex = env->ExceptionOccurred();
- env->ExceptionClear();
- m_ownerResource->removeStatusListener<JniSecurityStatusListener>(env, m_jwListener);
- env->Throw((jthrowable)ex);
- }
- else
- {
- m_ownerResource->removeStatusListener<JniSecurityStatusListener>(env, m_jwListener);
- }
-}
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2016 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.
- *
- ******************************************************************/
-
-#ifndef __JNI_ES_SECURITY_PROVISIONING_STATUS_LISTENER_H_
-#define __JNI_ES_SECURITY_PROVISIONING_STATUS_LISTENER_H_
-
-#include <jni.h>
-
-#include "RemoteEnrollee.h"
-#include "ESRichCommon.h"
-
-#include "JniJvm.h"
-
-class JniRemoteEnrollee;
-
-using namespace OIC::Service;
-
-class JniSecurityStatusListener
-{
- public:
- /**
- * @brief constructor
- */
- JniSecurityStatusListener(JNIEnv *env, jobject jListener, JniRemoteEnrollee *resource);
-
- /**
- * @brief destructor
- */
- ~JniSecurityStatusListener();
-
- /**
- * @brief callback function that will be passed to Native layer
- */
- void secProvisionStatusCallback (std::shared_ptr<SecProvisioningStatus> secProvisioningStatus);
-
- private:
- jweak m_jwListener;
- JniRemoteEnrollee *m_ownerResource;
- void checkExAndRemoveListener(JNIEnv *env);
-};
-
-#endif //__JNI_ES_SECURITY_PROVISIONING_STATUS_LISTENER_H_
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<module type="JAVA_MODULE" version="4">
- <component name="FacetManager">
- <facet type="android" name="Android">
- <configuration />
- </facet>
- </component>
- <component name="NewModuleRootManager" inherit-compiler-output="true">
- <exclude-output />
- <content url="file://$MODULE_DIR$">
- <sourceFolder url="file://$MODULE_DIR$/java" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/gen" isTestSource="false" generated="true" />
- </content>
- <orderEntry type="jdk" jdkName="Android API 21 Platform" jdkType="Android SDK" />
- <orderEntry type="sourceFolder" forTests="false" />
- <orderEntry type="library" name="classes1" level="project" />
- </component>
-</module>
\ No newline at end of file
+++ /dev/null
-<resources>
-
- <string name="app_name">EasySetupCore</string>
-
-</resources>
+++ /dev/null
-<resources>
-
- <!--
- Base application theme, dependent on API level. This theme is replaced
- by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
- -->
- <style name="AppBaseTheme" parent="android:Theme.Light">
- <!--
- Theme customizations available in newer API levels can go in
- res/values-vXX/styles.xml, while customizations related to
- backward-compatibility can go here.
- -->
- </style>
-
- <!-- Application theme. -->
- <style name="AppTheme" parent="AppBaseTheme">
- <!-- All customizations that are NOT specific to a particular API-level can go here. -->
- </style>
-
-</resources>
+++ /dev/null
-#//******************************************************************
-#//
-#// Copyright 2016 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.
-#//
-#//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-import os
-import platform
-Import('env')
-
-android_home = env.get('ANDROID_HOME')
-
-ANDROID_TARGET_ARCH = env.get('TARGET_ARCH')
-if env.get('RELEASE'):
- ANDROID_RELEASE="release"
-else:
- ANDROID_RELEASE="debug"
-
-os.environ['ANDROID_HOME'] = env.get('ANDROID_HOME')
-os.environ['ANDROID_NDK_HOME'] = env.get('ANDROID_NDK')
-
-if not os.path.exists(android_home + '/platforms/android-21') or not os.path.exists(android_home + '/build-tools/20.0.0'):
- print '''
-***************************************** Info ********************************
-* Either 'Android API 21' is not installed or 'Android SDK Build Tools *
-* 20.0.0' is not installed. The Android SDK Manager will now open. Please *
-* be sure to deselect all options, then select the following 2 packages: *
-* 1. Under "Tools" select "Android SDK Build-tools" Revision 20. *
-* 2. Under "Android 5.0.1 (API 21)" select "SDK Platform" *
-* 3. Continue by selecting "Install 2 Packages" *
-* *
-* NOTE: If you have an http proxy, please press ctrl+c now and edit/create *
-* the following file in your $HOME directory as follows: *
-* *
-* Edit/Create file: "$HOME/.android/androidtool.cfg" *
-* *
-* http.proxyPort=<YOUR_PORT_NUMBER> *
-* sdkman.monitor.density=108 *
-* http.proxyHost=<YOUR_HTTP_PROXY_ADDRESS> *
-* sdkman.show.update.only=true *
-* sdkman.ask.adb.restart=false *
-* sdkman.force.http=true *
-* sdkman.show.updateonly=true *
-* *
-*******************************************************************************
-
-...Opening Android SDK Manager now. Once you are finished, the build will continue.
-'''
- os.system(android_home + '/tools/android')
-
-#SConscript("../../../../../../android/android_api/SConscript")
-
-def ensure_libs(target, source, env):
- return target, [source, env.get('BUILD_DIR') + 'liboc.so', env.get('BUILD_DIR') + 'liboc_logger.so']
-
-jdk_env = Environment(ENV=os.environ)
-jdk_env['BUILDERS']['Gradle'] = Builder(action = env.get('ANDROID_GRADLE') +
- ' build -bservice/easy-setup/mediator/richsdk/android/build.gradle -PTARGET_ARCH=%s -PRELEASE=%s --stacktrace' %(ANDROID_TARGET_ARCH, ANDROID_RELEASE),
- emitter = ensure_libs)
-jdk_env['BUILD_DIR'] = env.get('BUILD_DIR')
-cmdBuildEasysetup=jdk_env.Gradle(target="EasySetupCore/objs",
- source="EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/EasySetup.java")
-
-Depends(cmdBuildEasysetup, env.get('baseAAR'))
-
-env.AppendUnique(easysetupAAR = cmdBuildEasysetup)
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<module external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$" external.system.id="GRADLE" external.system.module.group="" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
- <component name="FacetManager">
- <facet type="java-gradle" name="Java-Gradle">
- <configuration>
- <option name="BUILD_FOLDER_PATH" value="$MODULE_DIR$/build" />
- </configuration>
- </facet>
- </component>
- <component name="NewModuleRootManager" inherit-compiler-output="true">
- <exclude-output />
- <content url="file://$MODULE_DIR$">
- <excludeFolder url="file://$MODULE_DIR$/.gradle" />
- </content>
- <orderEntry type="inheritedJdk" />
- <orderEntry type="sourceFolder" forTests="false" />
- </component>
-</module>
-
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2016 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.
- *
- ******************************************************************/
-// Top-level build file where you can add configuration options common to all sub-projects/modules.
-
-buildscript {
- repositories {
- jcenter()
- }
- dependencies {
- classpath 'com.android.tools.build:gradle:1.3.0'
-
- // NOTE: Do not place your application dependencies here; they belong
- // in the individual module build.gradle files
- }
-}
-
-allprojects {
- repositories {
- jcenter {
- url "http://jcenter.bintray.com/"
- }
- flatDir {
- dirs "../../../../../../android/android_api/base/build/outputs/aar/"
- }
- }
-}
+++ /dev/null
-#
-# //******************************************************************
-# //
-# // Copyright 2015 Intel Corporation.
-# //
-# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-# //
-# // 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.
-# //
-# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#
-
-# Project-wide Gradle settings.
-
-# IDE (e.g. Android Studio) users:
-# Gradle settings configured through the IDE *will override*
-# any settings specified in this file.
-
-# For more details on how to configure your build environment visit
-# http://www.gradle.org/docs/current/userguide/build_environment.html
-
-# Specifies the JVM arguments used for the daemon process.
-# The setting is particularly useful for tweaking memory settings.
-# Default value: -Xmx10248m -XX:MaxPermSize=256m
-# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
-
-# When configured, Gradle will run in incubating parallel mode.
-# This option should only be used with decoupled projects. More details, visit
-# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
-# org.gradle.parallel=true
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2016 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 ':EasySetupCore'
+++ /dev/null
-#built application files\r
-*.apk\r
-*.ap_\r
-\r
-# files for the dex VM\r
-*.dex\r
-\r
-# Java class files\r
-*.class\r
-\r
-# generated files\r
-bin/\r
-gen/\r
-\r
-# Local configuration file (sdk path, etc)\r
-local.properties\r
-\r
-# Proguard folder generated by Eclipse \r
-proguard/ \r
-\r
-# Windows thumbnail db\r
-Thumbs.db\r
-\r
-# OSX files\r
-.DS_Store\r
-\r
-# Eclipse project files\r
-.classpath\r
-.project\r
-\r
-#Android Studio & Gradle\r
-.gradle\r
-/local.properties\r
-/.idea/workspace.xml\r
-/.idea/libraries\r
-.DS_Store\r
-/build/*\r
-/base/build/*\r
-/base/obj/*\r
-/base/libs/*\r
-/sample/*\r
-\r
-#Some older projects\r
-/*/out\r
-/*/*/build\r
-/*/*/production\r
-*.iws\r
-*.ipr\r
-*~\r
-*.swp
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>\r
-<module external.linked.project.id="EasySetup" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$" external.system.id="GRADLE" external.system.module.group="" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">\r
- <component name="FacetManager">\r
- <facet type="java-gradle" name="Java-Gradle">\r
- <configuration>\r
- <option name="BUILD_FOLDER_PATH" value="$MODULE_DIR$/build" />\r
- <option name="BUILDABLE" value="false" />\r
- </configuration>\r
- </facet>\r
- </component>\r
- <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_7" inherit-compiler-output="true">\r
- <exclude-output />\r
- <content url="file://$MODULE_DIR$">\r
- <excludeFolder url="file://$MODULE_DIR$/.gradle" />\r
- </content>\r
- <orderEntry type="inheritedJdk" />\r
- <orderEntry type="sourceFolder" forTests="false" />\r
- </component>\r
-</module>\r
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<module external.linked.project.id="EasySetupGradle" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$" external.system.id="GRADLE" external.system.module.group="" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
- <component name="FacetManager">
- <facet type="java-gradle" name="Java-Gradle">
- <configuration>
- <option name="BUILD_FOLDER_PATH" value="$MODULE_DIR$/build" />
- <option name="BUILDABLE" value="false" />
- </configuration>
- </facet>
- </component>
- <component name="NewModuleRootManager" inherit-compiler-output="true">
- <exclude-output />
- <content url="file://$MODULE_DIR$">
- <excludeFolder url="file://$MODULE_DIR$/.gradle" />
- </content>
- <orderEntry type="inheritedJdk" />
- <orderEntry type="sourceFolder" forTests="false" />
- </component>
-</module>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<module external.linked.project.id=":app" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$/.." external.system.id="GRADLE" external.system.module.group="EasySetup" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
- <component name="FacetManager">
- <facet type="android-gradle" name="Android-Gradle">
- <configuration>
- <option name="GRADLE_PROJECT_PATH" value=":app" />
- </configuration>
- </facet>
- <facet type="android" name="Android">
- <configuration>
- <option name="SELECTED_BUILD_VARIANT" value="debug" />
- <option name="SELECTED_TEST_ARTIFACT" value="_android_test_" />
- <option name="ASSEMBLE_TASK_NAME" value="assembleDebug" />
- <option name="COMPILE_JAVA_TASK_NAME" value="compileDebugSources" />
- <option name="ASSEMBLE_TEST_TASK_NAME" value="assembleDebugAndroidTest" />
- <option name="COMPILE_JAVA_TEST_TASK_NAME" value="compileDebugAndroidTestSources" />
- <afterSyncTasks>
- <task>generateDebugAndroidTestSources</task>
- <task>generateDebugSources</task>
- </afterSyncTasks>
- <option name="ALLOW_USER_CONFIGURATION" value="false" />
- <option name="MANIFEST_FILE_RELATIVE_PATH" value="/src/main/AndroidManifest.xml" />
- <option name="RES_FOLDER_RELATIVE_PATH" value="/src/main/res" />
- <option name="RES_FOLDERS_RELATIVE_PATH" value="file://$MODULE_DIR$/src/main/res" />
- <option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" />
- </configuration>
- </facet>
- </component>
- <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_7" inherit-compiler-output="false">
- <output url="file://$MODULE_DIR$/build/intermediates/classes/debug" />
- <output-test url="file://$MODULE_DIR$/build/intermediates/classes/androidTest/debug" />
- <exclude-output />
- <content url="file://$MODULE_DIR$">
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/debug" isTestSource="false" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/debug" isTestSource="false" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/debug" isTestSource="false" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/debug" isTestSource="false" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/debug" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/debug" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/androidTest/debug" isTestSource="true" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/androidTest/debug" isTestSource="true" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/androidTest/debug" isTestSource="true" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/androidTest/debug" isTestSource="true" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/androidTest/debug" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/androidTest/debug" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/res" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/resources" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/assets" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/aidl" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/java" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/jni" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/rs" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/res" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/assets" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/aidl" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/jni" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/rs" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/res" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/resources" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/assets" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/aidl" isTestSource="true" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/java" isTestSource="true" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/jni" isTestSource="true" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/rs" isTestSource="true" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/assets" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/bundles" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/classes" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/coverage-instrumented-classes" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dependency-cache" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex-cache" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/exploded-aar/EasySetup/EasySetupCore-debug/unspecified/jars" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/exploded-aar/EasySetup/iotivity-armeabi-base-debug/unspecified/jars" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/jacoco" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/javaResources" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/libs" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/lint" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/manifests" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/ndk" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/pre-dexed" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/proguard" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/res" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/rs" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/symbols" />
- <excludeFolder url="file://$MODULE_DIR$/build/outputs" />
- <excludeFolder url="file://$MODULE_DIR$/build/tmp" />
- </content>
- <orderEntry type="jdk" jdkName="Android API 21 Platform" jdkType="Android SDK" />
- <orderEntry type="sourceFolder" forTests="false" />
- <orderEntry type="module" module-name="EasySetupCore-debug" exported="" />
- <orderEntry type="module" module-name="iotivity-armeabi-base-debug" exported="" />
- <orderEntry type="library" exported="" name="EasySetupCore-debug-unspecified" level="project" />
- <orderEntry type="library" exported="" name="iotivity-armeabi-base-debug-unspecified" level="project" />
- </component>
-</module>
\ No newline at end of file
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2016 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-apply plugin: 'com.android.application'
-
-android {
- compileSdkVersion 21
- buildToolsVersion "20.0.0"
-
- defaultConfig {
- applicationId "org.iotivity.service.easysetup"
- minSdkVersion 21
- targetSdkVersion 21
- versionCode 1
- versionName "1.0"
- }
- buildTypes {
- release {
- minifyEnabled false
- proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
- }
- }
- lintOptions {
- abortOnError false
- }
-}
-repositories {
- flatDir {
- dirs "../../../../../../../android/android_api/base/build/outputs/aar/", "../../../../../mediator/richsdk/android/EasySetupCore/build/outputs/aar/"
- }
-}
-
-try {
- dependencies {
- compile ":iotivity-base-${TARGET_ARCH}-${RELEASE}@aar"
- compile ":EasySetupCore-${RELEASE}@aar"
- }
-} catch (all) {
- print "${ERROR_MSG}"
- assert all
-}
+++ /dev/null
-# Add project specific ProGuard rules here.
-# By default, the flags in this file are appended to flags specified
-# in /home/rahul/sdk/tools/proguard/proguard-android.txt
-# You can edit the include path and order by changing the proguardFiles
-# directive in build.gradle.
-#
-# For more details, see
-# http://developer.android.com/guide/developing/tools/proguard.html
-
-# Add any project specific keep options here:
-
-# If your project uses WebView with JS, uncomment the following
-# and specify the fully qualified class name to the JavaScript interface
-# class:
-#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
-# public *;
-#}
+++ /dev/null
-<?xml version="1.0" encoding="utf-8"?>
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="org.iotivity.service.easysetup"
- android:versionCode="1"
- android:versionName="1.0">
-
- <uses-permission android:name="android.permission.INTERNET" />
- <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
- <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
- <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
- <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
-
- <uses-feature
- android:name="android.hardware.touchscreen"
- android:required="false" />
-
- <application
- android:allowBackup="true"
- android:icon="@drawable/ic_launcher"
- android:label="@string/app_name"
- android:theme="@style/AppTheme">
- <activity
- android:name=".LoginActivity"
- android:label="@string/app_name">
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- </intent-filter>
- </activity>
- <activity android:name=".EasysetupActivity" android:label="@string/app_name">
- <intent-filter>
- <action android:name="android.intent.action.MAIN"/>
- <category android:name="android.intent.category.LAUNCHER"/>
- </intent-filter>
- </activity>
- </application>
-
-</manifest>
+++ /dev/null
-{\r
- "acl": {\r
- "aclist": {\r
- "aces": [\r
- {\r
- "subjectuuid": "*",\r
- "resources": [\r
- {\r
- "href": "/oic/res",\r
- "rel": "",\r
- "rt": ["oic.wk.res"],\r
- "if": ["oic.if.ll"]\r
- },\r
- {\r
- "href": "/oic/d",\r
- "rel": "",\r
- "rt": ["oic.wk.d"],\r
- "if": ["oic.if.baseline", "oic.if.r"]\r
- },\r
- {\r
- "href": "/oic/p",\r
- "rel": "",\r
- "rt": ["oic.wk.p"],\r
- "if": ["oic.if.baseline", "oic.if.r"]\r
- },\r
- {\r
- "href": "/oic/ad",\r
- "rel": "",\r
- "rt": ["oic.wk.ad"],\r
- "if": ["oic.if.baseline"]\r
- },\r
- {\r
- "href": "/oic/sec/acl",\r
- "rel": "",\r
- "rt": ["oic.r.acl"],\r
- "if": ["oic.if.baseline"]\r
- },\r
- {\r
- "href": "/oic/res/types/d",\r
- "rel": "",\r
- "rt": ["oic.wk.res"],\r
- "if": ["oic.if.baseline"]\r
- }\r
- ],\r
- "permission": 2\r
- },\r
- {\r
- "subjectuuid": "*",\r
- "resources": [\r
- {\r
- "href": "/oic/sec/doxm",\r
- "rel": "",\r
- "rt": ["oic.r.doxm"],\r
- "if": ["oic.if.baseline"]\r
- },\r
- {\r
- "href": "/oic/sec/pstat",\r
- "rel": "",\r
- "rt": ["oic.r.pstat"],\r
- "if": ["oic.if.baseline"]\r
- }\r
- ],\r
- "permission": 2\r
- }\r
- ]\r
- },\r
- "rowneruuid" : "61646d69-6e44-6576-6963-655575696430"\r
- },\r
- "pstat": {\r
- "isop": true,\r
- "deviceuuid": "61646d69-6e44-6576-6963-655575696430",\r
- "rowneruuid": "61646d69-6e44-6576-6963-655575696430",\r
- "cm": 0,\r
- "tm": 0,\r
- "om": 3,\r
- "sm": 3\r
- },\r
- "doxm": {\r
- "oxms": [0],\r
- "oxmsel": 0,\r
- "sct": 1,\r
- "owned": true,\r
- "deviceuuid": "61646d69-6e44-6576-6963-655575696430",\r
- "devowneruuid": "61646d69-6e44-6576-6963-655575696430",\r
- "rowneruuid": "61646d69-6e44-6576-6963-655575696430",\r
- "x.com.samsung.dpc": false\r
- }\r
-}\r
+++ /dev/null
-/**
- * ***************************************************************
- * <p/>
- * Copyright 2016 Samsung Electronics All Rights Reserved.
- * <p/>
- * <p/>
- * <p/>
- * 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
- * <p/>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p/>
- * 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.
- * <p/>
- * ****************************************************************
- */
-
-package org.iotivity.service.easysetup;
-
-import android.app.Activity;
-import android.content.Context;
-import android.content.Intent;
-import android.content.SharedPreferences;
-import android.os.Bundle;
-import android.preference.PreferenceManager;
-import android.util.Log;
-import android.view.View;
-import android.widget.ArrayAdapter;
-import android.widget.Button;
-import android.widget.EditText;
-import android.widget.LinearLayout;
-import android.widget.RadioButton;
-import android.widget.RadioGroup;
-import android.widget.Spinner;
-import android.widget.TextView;
-import android.widget.Toast;
-import android.widget.ToggleButton;
-
-import org.iotivity.base.ErrorCode;
-import org.iotivity.base.ModeType;
-import org.iotivity.base.OcConnectivityType;
-import org.iotivity.base.OcException;
-import org.iotivity.base.OcHeaderOption;
-import org.iotivity.base.ObserveType;
-import org.iotivity.base.OcPlatform;
-import org.iotivity.base.OcPresenceStatus;
-import org.iotivity.base.OcProvisioning;
-import org.iotivity.base.OcRepresentation;
-import org.iotivity.base.OcResource;
-import org.iotivity.base.PlatformConfig;
-import org.iotivity.base.QualityOfService;
-import org.iotivity.base.ServiceType;
-import org.iotivity.base.OcAccountManager;
-import org.iotivity.service.easysetup.mediator.ESConstants;
-import org.iotivity.service.easysetup.mediator.CloudProp;
-import org.iotivity.service.easysetup.mediator.CloudPropProvisioningCallback;
-import org.iotivity.service.easysetup.mediator.CloudPropProvisioningStatus;
-import org.iotivity.service.easysetup.mediator.DevicePropProvisioningCallback;
-import org.iotivity.service.easysetup.mediator.DevicePropProvisioningStatus;
-import org.iotivity.service.easysetup.mediator.ESException;
-import org.iotivity.service.easysetup.mediator.EasySetup;
-import org.iotivity.service.easysetup.mediator.GetConfigurationCallback;
-import org.iotivity.service.easysetup.mediator.GetConfigurationStatus;
-import org.iotivity.service.easysetup.mediator.RemoteEnrollee;
-import org.iotivity.service.easysetup.mediator.SecurityProvisioningCallback;
-import org.iotivity.service.easysetup.mediator.SecurityProvisioningStatus;
-import org.iotivity.service.easysetup.mediator.enums.ESCloudProvState;
-import org.iotivity.service.easysetup.mediator.enums.ESResult;
-import org.iotivity.service.easysetup.mediator.enums.WIFI_AUTHTYPE;
-import org.iotivity.service.easysetup.mediator.enums.WIFI_ENCTYPE;
-import org.iotivity.service.easysetup.mediator.enums.WIFI_FREQ;
-import org.iotivity.service.easysetup.mediator.enums.WIFI_MODE;
-import org.iotivity.service.easysetup.mediator.samsung.SCDeviceProp;
-import org.iotivity.service.easysetup.mediator.samsung.SCEnrolleeConf;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.EnumSet;
-import java.util.HashMap;
-import java.util.List;
-
-
-public class EasysetupActivity extends Activity
- implements OcPlatform.OnPresenceListener,
- OcResource.OnObserveListener{
- private static final String TAG = "Easysetup Mediator: ";
- PlatformConfig cfg;
- OcAccountManager m_accountManager = null;
- final String deviceID = "9E09F4FE-978A-4BC3-B356-1F93BCA37829";
- final String samsungCIServer = "coap+tcp://52.69.149.85:5683";
-
- private static final int BUFFER_SIZE = 1024;
-
- private String filePath = "";
- public static final String OIC_CLIENT_JSON_DB_FILE = "oic_svr_db_client.dat";
- public static final String OIC_SQL_DB_FILE = "PDM.db";
-
- private boolean isFirstTime = true;
- String mEnrolleeDeviceID;
- String mAuthCode;
- String mAuthProvider;
- String mRefreshtoken;
- String mUserID;
- String mAccessToken;
- String mEnrolleeAuthCode;
-
- ToggleButton mSecurityMode;
-
- RadioGroup mEasysetupProcess;
- RadioButton mConfigureSecProcess;
- RadioButton mGetConfigurationProcess;
- RadioButton mProvisionDevPropProcess;
- RadioButton mProvisionCloudPropProcess;
-
- Button mDiscoverResource;
- Button mStartGetConfiguration;
- Button mStartConfigureSec;
- Button mStartProvisionDevProp;
- Button mStartProvisionCloudProp;
-
- TextView mGetconfigurationStateText;
- TextView mDevNameText;
- TextView mModelNumberText;
- TextView mDevTypeText;
- TextView mDevSubTypeText;
- TextView mWifiModeText;
- TextView mWifiFreqText;
- TextView mCloudAccessableText;
- TextView mSecStateText;
- TextView mSecDevIDText;
- TextView mProvisionDevPropState;
- TextView mProvisionCloudPropState;
-
- EditText mEnrollerSsidText;
- EditText mEnrollerPWText;
- EditText mInputLanguageText;
- EditText mInputCountryText;
- EditText mInputLocationText;
- EditText mDiscoveryChannelText;
- EditText mAddrText;
- EditText mZipCodeText;
- EditText mBuildingText;
- EditText mAuthCodeText;
- EditText mAuthProviderText;
- EditText mCIServerText;
-
- LinearLayout mGetConfigurationInfo;
- LinearLayout mConfigureSecInfo;
- LinearLayout mProvisionDevPropInfo;
- LinearLayout mProvisionCloudPropInfo;
-
- Spinner mAuthType;
- Spinner mEncType;
-
- EasySetup mEasySetup;
- RemoteEnrollee mRemoteEnrollee;
-
- Activity mActivity;
- Context mContext;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.easysetup_main);
-
- mActivity = EasysetupActivity.this;
- mContext = mActivity.getBaseContext();
-
- mSecurityMode = (ToggleButton) findViewById(R.id.btn_Security);
-
- mEasysetupProcess = (RadioGroup) findViewById(R.id.rg_EasysetupProcess);
-
- mConfigureSecProcess = (RadioButton) findViewById(R.id.btn_configurSec);
- mGetConfigurationProcess = (RadioButton) findViewById(R.id.btn_getConfiguration);
- mProvisionDevPropProcess = (RadioButton) findViewById(R.id.btn_provisionDevConf);
- mProvisionCloudPropProcess =
- (RadioButton) findViewById(R.id.btn_provisionCloudConf);
-
- mDiscoverResource = (Button) findViewById(R.id.btn_discoverResource);
- mStartGetConfiguration =
- (Button) findViewById(R.id.btn_startGetConfiguration);
- mStartConfigureSec = (Button) findViewById(R.id.btn_startConfigureSec);
- mStartProvisionDevProp = (Button) findViewById(R.id.btn_startProvisionDevConf);
- mStartProvisionCloudProp = (Button) findViewById(R.id.btn_startProvisionCloudConf);
-
- mGetconfigurationStateText =
- (TextView) findViewById(R.id.txt_getConfigurationState);
- mDevNameText = (TextView) findViewById(R.id.txt_devName);
- mModelNumberText = (TextView) findViewById(R.id.txt_modelNumber);
- mDevTypeText = (TextView) findViewById(R.id.txt_devType);
- mDevSubTypeText = (TextView) findViewById(R.id.txt_devSubType);
- mWifiModeText = (TextView) findViewById(R.id.txt_wifiMode);
- mWifiFreqText = (TextView) findViewById(R.id.txt_wifiFreq);
- mCloudAccessableText = (TextView) findViewById(R.id.txt_cloudAccessable);
- mSecStateText = (TextView) findViewById(R.id.txt_secState);
- mSecDevIDText = (TextView) findViewById(R.id.txt_secDevID);
- mProvisionDevPropState = (TextView) findViewById(R.id.txt_provisionDevConfState);
- mProvisionCloudPropState =
- (TextView) findViewById(R.id.txt_provisionCloudConfState);
-
- mEnrollerSsidText = (EditText) findViewById(R.id.editText_EnrollerSSID);
- mEnrollerPWText = (EditText) findViewById(R.id.editText_EnrollerPW);
- mInputLanguageText = (EditText) findViewById(R.id.editText_Language);
- mInputCountryText = (EditText) findViewById(R.id.editText_Country);
- mInputLocationText = (EditText) findViewById(R.id.editText_Location);
- mDiscoveryChannelText = (EditText) findViewById(R.id.editText_DiscoveryChannel);
- mAddrText = (EditText) findViewById(R.id.editText_LocationAddr);
- mZipCodeText = (EditText) findViewById(R.id.editText_LocationZip);
- mBuildingText = (EditText) findViewById(R.id.editText_LocationBuilding);
- mAuthCodeText = (EditText) findViewById(R.id.editText_authcode);
- mAuthProviderText = (EditText) findViewById(R.id.editText_authprovider);
- mCIServerText = (EditText) findViewById(R.id.editText_ciserver);
-
- mGetConfigurationInfo =
- (LinearLayout) findViewById(R.id.layout_GetConfiguration);
- mConfigureSecInfo = (LinearLayout) findViewById(R.id.layout_ConfigurSec);
- mProvisionDevPropInfo = (LinearLayout) findViewById(R.id.layout_ProvisionDevConf);
- mProvisionCloudPropInfo = (LinearLayout) findViewById(R.id.layout_ProvisionCloudConf);
-
- mAuthType = (Spinner) findViewById(R.id.spinner_authType);
- mEncType = (Spinner) findViewById(R.id.spinner_encType);
-
- mEasysetupProcess.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
- @Override
- public void onCheckedChanged(RadioGroup group, int checkedId) {
- mGetConfigurationInfo.setVisibility(View.GONE);
- mConfigureSecInfo.setVisibility(View.GONE);
- mProvisionDevPropInfo.setVisibility(View.GONE);
- mProvisionCloudPropInfo.setVisibility(View.GONE);
-
- switch (checkedId) {
- case R.id.btn_configurSec:
- mConfigureSecInfo.setVisibility(View.VISIBLE);
- break;
-
- case R.id.btn_getConfiguration:
- mGetConfigurationInfo.setVisibility(View.VISIBLE);
- break;
-
- case R.id.btn_provisionDevConf:
- mProvisionDevPropInfo.setVisibility(View.VISIBLE);
- break;
-
- case R.id.btn_provisionCloudConf:
- Log.d(TAG, "Starting login activity");
- Intent intent = new Intent(EasysetupActivity.this, LoginActivity.class);
- startActivityForResult(intent, 2);
- mProvisionCloudPropInfo.setVisibility(View.VISIBLE);
- break;
- }
- }
- });
-
- ArrayAdapter<CharSequence> adAuthType, adEnctype;
-
- adAuthType = ArrayAdapter.createFromResource(this, R.array.auth_type,
- android.R.layout.simple_spinner_item);
- adAuthType.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
-
- adEnctype = ArrayAdapter.createFromResource(this, R.array.enc_type,
- android.R.layout.simple_spinner_item);
- adEnctype.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
-
- mAuthType.setAdapter(adAuthType);
- mAuthType.setSelection(0);
-
- mEncType.setAdapter(adEnctype);
- mEncType.setSelection(0);
-
- addListenerForDiscoverEnrollee();
- addListenerForStartConfigureSec();
- addListenerForStartGetConfiguration();
- addListenerForStartProvisionDevProp();
- addListenerForStartProvisionCloudProp();
-
- mSecurityMode.setClickable(false);
- mConfigureSecProcess.setEnabled(false);
- mGetConfigurationProcess.setEnabled(false);
- mProvisionDevPropProcess.setEnabled(false);
- mProvisionCloudPropProcess.setEnabled(false);
-
- mEasySetup = EasySetup.getInstance(getApplicationContext());
-
- initOICStack();
-
- try {
- m_accountManager = OcPlatform.constructAccountManagerObject(
- samsungCIServer,
- EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP));
-
- Log.e(TAG, "constructAccountManagerObject is successful");
- } catch (OcException e) {
- Log.e(TAG, e.toString());
- Log.e(TAG,"Failed to constructAccountManagerObject");
- }
- SharedPreferences settings =
- getApplicationContext().getSharedPreferences("IoTivityCloud", 0);
- mAccessToken = settings.getString("accesstoken", null);
- mRefreshtoken = settings.getString("refreshtoken", null);
- mUserID = settings.getString("uid", null);
-
- if(mRefreshtoken == null)
- {
- Log.d(TAG, "Can not find refresh token");
- }
-
- if(mAccessToken == null && mRefreshtoken == null)
- {
- /* Samsung account */
- Log.d(TAG, "Starting login activity");
-
- Intent intent = new Intent(EasysetupActivity.this, LoginActivity.class);
- startActivityForResult(intent, 1);
- }
- else if(mAccessToken != null)
- {
- SignInDevice();
- }
- }
-
- private void initOICStack() {
- filePath = getFilesDir().getPath() + "/";
-
- SharedPreferences wmbPreference = PreferenceManager.getDefaultSharedPreferences
- (getApplicationContext());
- boolean isFirstRun = wmbPreference.getBoolean("FIRSTRUN", true);
- if (isFirstRun) {
- if(!copyJsonFromAsset())
- {
- Log.e(TAG, "initOICStack error: " + "copyJsonFromAsset()");
- Toast.makeText(this,"Can't Copy DB file from asset, please retry start SampleApp.",
- Toast.LENGTH_LONG).show();
- return;
- }
- SharedPreferences.Editor editor = wmbPreference.edit();
- editor.putBoolean("FIRSTRUN", false);
- editor.commit();
- }
-
- cfg = new PlatformConfig(
- this,
- ServiceType.IN_PROC,
- ModeType.CLIENT_SERVER,
- "0.0.0.0", // bind to all available interfaces
- 0,
- QualityOfService.LOW, filePath + OIC_CLIENT_JSON_DB_FILE);
- try {
- /*
- * Initialize DataBase
- */
-
- OcPlatform.Configure(cfg);
-
- String sqlDbPath = getFilesDir().getAbsolutePath().replace("files", "databases") +
- File.separator;
- File file = new File(sqlDbPath);
- //check files directory exists
- if (!(file.isDirectory())) {
- file.mkdirs();
- Log.d(TAG, "Sql db directory created at " + sqlDbPath);
- }
- Log.d(TAG, "Sql db directory exists at " + sqlDbPath);
-
- //SQLiteDatabase.openOrCreateDatabase(sqlDbPath+ OIC_SQL_DB_FILE, null);
- OcProvisioning.provisionInit(sqlDbPath + OIC_SQL_DB_FILE);
- mSecurityMode.setChecked(true);
- } catch (OcException e) {
- logMessage(TAG + "provisionInit error: " + e.getMessage());
- Log.e(TAG, e.getMessage());
- Toast.makeText(this,"provisionInit error: " + e.getMessage(),
- Toast.LENGTH_LONG).show();
- mSecurityMode.setChecked(false);
- return;
- } catch (UnsatisfiedLinkError e) {
-
- // Note : Easy setup is built with SECURED = 0, but user still selects Security feature
- // while running the Mediator App it couldn't find "libocprovision.so".
- // As per the programmer guide, security feature should be invoked only if build is done with SECURED = 1.
- mSecurityMode.setChecked(false);
- Log.e(TAG, " Easy setup is built with secured = 0, but executed with security feature");
- Toast.makeText(this,"Security is not enabled [Easy setup is built with SECURED = 0]",
- Toast.LENGTH_LONG).show();
- return;
- }
- }
-
- OcPlatform.OnResourceFoundListener listener =
- new OcPlatform.OnResourceFoundListener() {
- @Override
- public void onFindResourceFailed(Throwable throwable, String s) {
- Log.e(TAG, "Failed found resource, ecode: " + s);
- }
- @Override
- public void onResourceFound(OcResource ocResource) {
- synchronized (mActivity) {
- if(isFirstTime){
- if (null == ocResource) {
- Log.e(TAG, "Found resource is invalid");
- return;
- }
-
- if(ocResource.getHost().contains("coap+tcp")) {
- Log.d(TAG, "Recv Found resource event from tcp port," +
- "ignoring URI : " + ocResource.getUri());
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- mDiscoverResource.setEnabled(true);
- }
- });
- return;
- }
-
- // Get the resource URI
- String resourceUri = ocResource.getUri();
- // Get the resource host address
- String hostAddress = ocResource.getHost();
- Log.d(TAG,"URI of the resource: " + resourceUri);
- Log.d(TAG,"Host address of the resource: " + hostAddress);
-
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- mDiscoverResource.setText("Found");
- if(mSecurityMode.isChecked()) {
- mConfigureSecProcess.setEnabled(true);
- }
- mGetConfigurationProcess.setEnabled(true);
- mProvisionDevPropProcess.setEnabled(true);
- mProvisionCloudPropProcess.setEnabled(true);
- }
- });
- isFirstTime = false;
- mRemoteEnrollee = mEasySetup.createRemoteEnrollee(ocResource);
- mEnrolleeDeviceID = ocResource.getServerId();
- }
- }
- }
- };
-
- private void addListenerForDiscoverEnrollee() {
- mDiscoverResource.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- Thread thread = new Thread() {
- boolean result = true;
- @Override
- public void run() {
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- mDiscoverResource.setEnabled(false);
- }
- });
-
- try {
- String requestUri = OcPlatform.WELL_KNOWN_QUERY + "?rt=" + ESConstants.OC_RSRVD_ES_RES_TYPE_EASYSETUP;
- OcPlatform.findResource("",
- requestUri,
- EnumSet.of(OcConnectivityType.CT_DEFAULT),
- listener
- );
- }
- catch (OcException e) {
- e.printStackTrace();
- result = false;
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- mDiscoverResource.setEnabled(true);
- }
- });
- }
- }
- };
-
- thread.start();
- }
- });
- }
-
- private void addListenerForStartConfigureSec() {
- mStartConfigureSec.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- Thread thread = new Thread() {
- @Override
- public void run() {
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- mStartConfigureSec.setEnabled(false);
- }
- });
-
- try {
- mRemoteEnrollee.provisionSecurity(new SecurityProvisioningCallback() {
- @Override
- public void onProgress(final SecurityProvisioningStatus securityProvisioningStatus) {
- if(securityProvisioningStatus.getESResult() == ESResult.ES_OK) {
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- mSecStateText.setText("Success");
- mSecDevIDText.setText(securityProvisioningStatus.getDevUUID());
- }
- });
- }
- else if(securityProvisioningStatus.getESResult()
- == ESResult.ES_SECURE_RESOURCE_DISCOVERY_FAILURE) {
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- mSecStateText.setText("Not found Secure Resource");
- mStartConfigureSec.setEnabled(true);
- }
- });
- }
- else if(securityProvisioningStatus.getESResult()
- == ESResult.ES_OWNERSHIP_TRANSFER_FAILURE) {
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- mSecStateText.setText("Ownership transfer failed");
- mStartConfigureSec.setEnabled(true);
- }
- });
- }
- else {
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- mSecStateText.setText("Failed");
- mStartConfigureSec.setEnabled(true);
- }
- });
- }
- }
- });
- } catch (ESException e) {
- e.printStackTrace();
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- mStartConfigureSec.setEnabled(true);
- }
- });
- }
- }
- };
-
- thread.start();
- }
- });
- }
-
- private void addListenerForStartGetConfiguration(){
- mStartGetConfiguration.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- Thread thread = new Thread() {
- @Override
- public void run() {
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- mGetconfigurationStateText.setText("Process");
- mStartGetConfiguration.setEnabled(false);
- }
- });
-
- try {
- mRemoteEnrollee.getConfiguration(new GetConfigurationCallback() {
- @Override
- public void onProgress(GetConfigurationStatus getConfigurationStatus) {
- if(getConfigurationStatus.getESResult() == ESResult.ES_OK) {
-
- final SCEnrolleeConf scEnrolleeConf =
- new SCEnrolleeConf(getConfigurationStatus.getEnrolleeConf());
-
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- mGetconfigurationStateText.setText("Success");
- mDevNameText.setText(scEnrolleeConf.getDeviceName());
- mModelNumberText.setText(scEnrolleeConf.getModelNumber());
- mDevTypeText.setText(scEnrolleeConf.getDeviceType());
- mDevSubTypeText.setText(scEnrolleeConf.getDeviceSubType());
- setWifiModes(scEnrolleeConf.getWiFiModes());
- setWifiFreq(scEnrolleeConf.getWiFiFreq());
-
- if(scEnrolleeConf.isCloudAccessible()) {
- mCloudAccessableText.setText("TRUE");
- }
- else {
- mCloudAccessableText.setText("FALSE");
- }
- }
- });
- }
- else if(getConfigurationStatus.getESResult() == ESResult.ES_COMMUNICATION_ERROR)
- {
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- mGetconfigurationStateText.setText("Communication Error");
- mStartGetConfiguration.setEnabled(true);
- }
- });
- }
- else {
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- mGetconfigurationStateText.setText("Failed");
- mStartGetConfiguration.setEnabled(true);
- }
- });
- }
- }
- });
- } catch (ESException e) {
- e.printStackTrace();
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- mGetconfigurationStateText.setText("Failed");
- mStartGetConfiguration.setEnabled(true);
- }
- });
- }
- }
- };
-
- thread.start();
- }
- });
- }
-
- private void addListenerForStartProvisionDevProp() {
- mStartProvisionDevProp.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- Thread thread = new Thread() {
- @Override
- public void run() {
- try {
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- mProvisionDevPropState.setText("Progress");
- mStartProvisionDevProp.setEnabled(false);
- }
- });
-
- String enrollerSSID = mEnrollerSsidText.getText().toString();
- String enrollerPW = mEnrollerPWText.getText().toString();
- String discoveryChannel = mDiscoveryChannelText.getText().toString();
- String addr = mAddrText.getText().toString();
- String zipcode = mZipCodeText.getText().toString();
- String building = mBuildingText.getText().toString();
- WIFI_AUTHTYPE authType =
- WIFI_AUTHTYPE.fromInt(mAuthType.getSelectedItemPosition());
- WIFI_ENCTYPE encType =
- WIFI_ENCTYPE.fromInt(mEncType.getSelectedItemPosition());
- String inputLanguage = mInputLanguageText.getText().toString();
- String inputCountry = mInputCountryText.getText().toString();
- String inputLocation = mInputLocationText.getText().toString();
-
- ArrayList<String> locations = new ArrayList<String>();
- locations.add(addr);
- locations.add(zipcode);
- locations.add(building);
-
- SCDeviceProp scDevProp = new SCDeviceProp();
- scDevProp.setWiFiProp(enrollerSSID, enrollerPW, authType, encType);
- scDevProp.setDevConfProp(inputLanguage, inputCountry, inputLocation);
- scDevProp.setDiscoveryChannel(Integer.parseInt(discoveryChannel));
- scDevProp.setSCLocation(locations);
-
- mRemoteEnrollee.provisionDeviceProperties(scDevProp, new DevicePropProvisioningCallback() {
- @Override
- public void onProgress(DevicePropProvisioningStatus devPropProvisioningStatus) {
- final ESResult result = devPropProvisioningStatus.getESResult();
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- if(result.equals(ESResult.ES_OK)) {
- mProvisionDevPropState.setText("Success");
- }
- else if(result.equals(ESResult.ES_ERROR)) {
- mProvisionDevPropState.setText("Failed");
- }
- else if(result.equals(ESResult.ES_COMMUNICATION_ERROR)) {
- mProvisionDevPropState.setText("Communication Error");
- }
- mStartProvisionDevProp.setEnabled(true);
- }
- });
- }
- });
- } catch (ESException e) {
- e.printStackTrace();
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- mProvisionDevPropState.setText("Failed");
- mStartProvisionDevProp.setEnabled(true);
- }
- });
- }
- }
- };
-
- thread.start();
- }
- });
- }
-
- private void addListenerForStartProvisionCloudProp() {
- mStartProvisionCloudProp.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- Thread thread = new Thread() {
- @Override
- public void run() {
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- mProvisionCloudPropState.setText("Progress");
- mStartProvisionCloudProp.setEnabled(false);
- }
- });
-
- try {
- String authCode = mAuthCodeText.getText().toString();
- String authProvider = mAuthProviderText.getText().toString();
- String ciserver = samsungCIServer;
-
- CloudProp cloudProp = new CloudProp();
- cloudProp.setCloudProp(authCode, authProvider, ciserver);
- cloudProp.setCloudID("f002ae8b-c42c-40d3-8b8d-1927c17bd1b3");
- cloudProp.setCredID(1);
-
- mRemoteEnrollee.provisionCloudProperties(cloudProp, new CloudPropProvisioningCallback() {
- @Override
- public void onProgress(CloudPropProvisioningStatus cloudProvisioningStatus) {
- final ESResult result = cloudProvisioningStatus.getESResult();
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- if(result.equals(ESResult.ES_ENROLLEE_DISCOVERY_FAILURE)) {
- mProvisionCloudPropState.setText("Not Found Resource");
- }
- else if(result.equals(ESResult.ES_OK)) {
- mProvisionCloudPropState.setText("Cloud Provisioning succeeds");
- }
- else if(result.equals(ESResult.ES_ACL_PROVISIONING_FAILURE)){
- mProvisionCloudPropState.setText("ACL-provisioning fails");
- }
- else if(result.equals(ESResult.ES_CERT_PROVISIONING_FAILURE)){
- mProvisionCloudPropState.setText("CERT-provisioning fails");
- }
- else if(result.equals(ESResult.ES_COMMUNICATION_ERROR)){
- mProvisionCloudPropState.setText("Communication Error");
- }
- else {
- mProvisionCloudPropState.setText("Cloud Provisioning fails");
- }
- }
- });
- }
- });
- } catch (ESException e) {
- e.printStackTrace();
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- mProvisionCloudPropState.setText("Failed");
- mStartProvisionCloudProp.setEnabled(true);
- }
- });
- }
- }
- };
-
- thread.start();
- }
- });
- }
-
- private boolean copyJsonFromAsset() {
- InputStream inputStream = null;
- OutputStream outputStream = null;
- int length;
- byte[] buffer = new byte[BUFFER_SIZE];
- try {
- inputStream = getAssets().open(OIC_CLIENT_JSON_DB_FILE);
- File file = new File(filePath);
- //check files directory exists
- if (!(file.exists() && file.isDirectory())) {
- file.mkdirs();
- }
- outputStream = new FileOutputStream(filePath + OIC_CLIENT_JSON_DB_FILE);
- while ((length = inputStream.read(buffer)) != -1) {
- outputStream.write(buffer, 0, length);
- }
- } catch (NullPointerException e) {
- logMessage(TAG + "Null pointer exception " + e.getMessage());
- Log.e(TAG, e.getMessage());
- return false;
- } catch (FileNotFoundException e) {
- logMessage(TAG + "Json svr db file not found " + e.getMessage());
- Log.e(TAG, e.getMessage());
- return false;
- } catch (IOException e) {
- logMessage(TAG + OIC_CLIENT_JSON_DB_FILE + " file copy failed");
- Log.e(TAG, e.getMessage());
- return false;
- } finally {
- if (inputStream != null) {
- try {
- inputStream.close();
- } catch (IOException e) {
- Log.e(TAG, e.getMessage());
- return false;
- }
- }
- if (outputStream != null) {
- try {
- outputStream.close();
- } catch (IOException e) {
- Log.e(TAG, e.getMessage());
- return false;
- }
- }
- }
- return true;
- }
-
- public void logMessage(String text) {
-
- }
-
- public void setWifiModes(ArrayList<WIFI_MODE> types) {
- String temp = "WIFI - ";
-
- for(WIFI_MODE type : types) {
- if(type.equals(WIFI_MODE.WIFI_11A)) {
- temp = temp + "11A ";
- }
- else if(type.equals(WIFI_MODE.WIFI_11B)) {
- temp = temp + "11B ";
- }
- else if(type.equals(WIFI_MODE.WIFI_11G)) {
- temp = temp + "11G ";
- }
- else if(type.equals(WIFI_MODE.WIFI_11N)) {
- temp = temp + "11N ";
- }
- else if(type.equals(WIFI_MODE.WIFI_11AC)) {
- temp = temp + "11AC ";
- }
- }
- final String modeTypes = temp;
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- mWifiModeText.setText(modeTypes);
- }
- });
- }
-
- public void setWifiFreq(final WIFI_FREQ freq) {
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- if(freq.equals(WIFI_FREQ.WIFI_24G)) {
- mWifiFreqText.setText("2.4G");
- }
- else if(freq.equals(WIFI_FREQ.WIFI_5G)) {
- mWifiFreqText.setText("5G");
- }
- else if(freq.equals(WIFI_FREQ.WIFI_BOTH)) {
- mWifiFreqText.setText("2.4G & 5G");
- }
- }
- });
- }
-
- @Override
- public void onPresence(OcPresenceStatus status, int sequence, String host) {
- final String strStaus = status.getValue();
- Log.d(TAG, "Presence response: " + strStaus + " sequence: " + sequence + " host: " + host);
- runOnUiThread(new Runnable()
- {
- public void run() {
- Toast.makeText(EasysetupActivity.this, "Easy-Setup completed", Toast.LENGTH_SHORT).show();
- }
- });
- }
-
- @Override
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- super.onActivityResult(requestCode, resultCode, data);
- if(resultCode==RESULT_OK && requestCode==1){
- mAuthCode = data.getStringExtra("authCode");
- mAuthProvider = data.getStringExtra("authProvider");
- String text = "Received authCode= " + mAuthCode;
- Log.d(TAG, text);
- SignUpDevice();
- }
- else if(resultCode==RESULT_OK && requestCode==2)
- {
- mEnrolleeAuthCode = data.getStringExtra("authCode");
- mAuthCodeText.setText(mEnrolleeAuthCode);
- mAuthProviderText.setText("samsung");
- mAuthCodeText.setEnabled(false);
- mAuthProviderText.setEnabled(false);
- subscribeDevicePresence();
- }
- }
-
- OcResource.OnPostListener onRefreshTokenPost = new OcResource.OnPostListener() {
- @Override
- public void onPostCompleted(List<OcHeaderOption> list, OcRepresentation ocRepresentation) {
- Log.d(TAG, "onRefreshTokenPost..");
- try {
- mAccessToken = ocRepresentation.getValue("accesstoken");
- mRefreshtoken = ocRepresentation.getValue("refreshtoken");
-
- saveCloudTokenAtSharedPreferences();
- }
- catch (OcException e)
- {
- e.printStackTrace();
- }
-
- SignInDevice();
- }
-
- @Override
- public void onPostFailed(Throwable throwable) {
- Log.d(TAG, "onRefreshTokenPost failed..");
- }
- };
-
- public void RefreshToken() {
- try {
- OcResource authResource = OcPlatform.constructResourceObject(samsungCIServer, "/.well-known/ocf/account/tokenrefresh",
- EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP, OcConnectivityType.CT_IP_USE_V4),
- false, Arrays.asList("oic.wk.account"), Arrays.asList(OcPlatform.DEFAULT_INTERFACE));
- OcRepresentation rep = new OcRepresentation();
-
- runOnUiThread(new Runnable()
- {
- public void run() {
- Toast.makeText(EasysetupActivity.this, "RefreshToken in progress..", Toast.LENGTH_SHORT).show();
- }
- });
-
- rep.setValue("di", deviceID);
- rep.setValue("granttype", "refresh_token");
- rep.setValue("refreshtoken", mRefreshtoken);
- rep.setValue("uid", mUserID);
- authResource.post(rep, new HashMap<String, String>(), onRefreshTokenPost);
- }
- catch(OcException e)
- {
- e.printStackTrace();
- }
-
- Log.d(TAG, "No error while executing login");
- }
-
- private void saveCloudTokenAtSharedPreferences() {
- Log.d(TAG, "accesstoken: " + mAccessToken);
- SharedPreferences settings = getApplicationContext().getSharedPreferences("IoTivityCloud", 0);
- SharedPreferences.Editor editor = settings.edit();
- editor.putString("accesstoken", mAccessToken);
- editor.putString("refreshtoken", mRefreshtoken);
- editor.putString("uid", mUserID);
-
- if(editor.commit() == true)
- Log.d(TAG, "accesstoken saved");
- else
- Log.d(TAG, "accesstoken not saved");
- }
-
- OcAccountManager.OnPostListener onSignUpPost = new OcAccountManager.OnPostListener() {
- @Override
- public void onPostCompleted(List<OcHeaderOption> list, OcRepresentation ocRepresentation) {
- Log.d(TAG, "onSignUpPost..");
- try {
- runOnUiThread(new Runnable()
- {
- public void run() {
- Toast.makeText(EasysetupActivity.this, "Sign-up completed", Toast.LENGTH_SHORT).show();
- }
- });
-
- mAccessToken = ocRepresentation.getValue("accesstoken");
- mRefreshtoken = ocRepresentation.getValue("refreshtoken");
- mUserID = ocRepresentation.getValue("uid");
-
- if(mAccessToken != null)
- {
- saveCloudTokenAtSharedPreferences();
- SignInDevice();
- }
- }
- catch (OcException e)
- {
- e.printStackTrace();
- }
- }
-
- @Override
- public void onPostFailed(Throwable throwable) {
- Log.d(TAG, "onSignUpPost failed.. : " + throwable.getMessage());
- }
- };
-
- private void SignUpDevice() {
- try {
- Log.d(TAG, "SignUpDevice..");
-
- runOnUiThread(new Runnable()
- {
- public void run() {
- Toast.makeText(EasysetupActivity.this, "SignUpDevice in progress..", Toast.LENGTH_SHORT).show();
- }
- });
-
- if(m_accountManager != null) {
- m_accountManager.signUp(mAuthProvider, mAuthCode, onSignUpPost);
- }
- }
- catch(OcException e)
- {
- e.printStackTrace();
- }
-
- Log.d(TAG, "No error while executing SignUp");
- }
-
- OcAccountManager.OnPostListener onSignInPost = new OcAccountManager.OnPostListener() {
- @Override
- public void onPostCompleted(List<OcHeaderOption> list, OcRepresentation ocRepresentation) {
- Log.d(TAG, "onSignInPost..");
-
- runOnUiThread(new Runnable()
- {
- public void run() {
- Toast.makeText(EasysetupActivity.this, "Sign-in completed", Toast.LENGTH_SHORT).show();
- }
- });
- }
-
- @Override
- public void onPostFailed(Throwable ex) {
- if (ex instanceof OcException) {
- OcException ocEx = (OcException) ex;
- ErrorCode errCode = ocEx.getErrorCode();
- Log.e(TAG, ocEx.getMessage());
- if (ErrorCode.UNAUTHORIZED_REQ != errCode) {
- RefreshToken();
- }
- }
- }
- };
-
- private void SignInDevice() {
- try {
- Log.d(TAG, "SignInDevice..");
-
- runOnUiThread(new Runnable()
- {
- public void run() {
- Toast.makeText(EasysetupActivity.this, "SignInDevice in progress..", Toast.LENGTH_SHORT).show();
- }
- });
- if(m_accountManager != null) {
- m_accountManager.signIn(mUserID, mAccessToken, onSignInPost);
- }
- }
- catch(OcException e)
- {
- e.printStackTrace();
- }
-
- Log.d(TAG, "No error while executing login");
- }
-
- @Override
- public void onObserveCompleted(List<OcHeaderOption> list, OcRepresentation ocRepresentation, int i) {
- Log.d(TAG,"onObserveCompleted");
- }
-
- @Override
- public void onObserveFailed(Throwable throwable) {
- Log.d(TAG,"onObserveFailed");
- }
-
- public void subscribeDevicePresence()
- {
- List<String> deviceIDs = new ArrayList<String>();
- deviceIDs.add(mEnrolleeDeviceID);
-
- try {
-
- OcPlatform.subscribeDevicePresence(samsungCIServer, deviceIDs, EnumSet.of(OcConnectivityType.
- CT_ADAPTER_TCP), this);
- } catch(OcException e)
- {
- e.printStackTrace();
- }
-
- }
-
- @Override
- protected void onDestroy() {
- super.onDestroy();
- }
-}
+++ /dev/null
-/**
- * ***************************************************************
- * <p/>
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- * <p/>
- * <p/>
- * <p/>
- * 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
- * <p/>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p/>
- * 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.
- * <p/>
- * ****************************************************************
- */
-
-package org.iotivity.service.easysetup;
-
-import android.app.Activity;
-import android.app.AlertDialog;
-import android.content.DialogInterface;
-import android.content.Intent;
-import android.content.SharedPreferences;
-import android.net.ConnectivityManager;
-import android.net.NetworkInfo;
-import android.net.UrlQuerySanitizer;
-import android.net.wifi.WifiConfiguration;
-import android.net.wifi.WifiManager;
-import android.os.Bundle;
-import android.os.Handler;
-import android.os.Message;
-import android.preference.PreferenceManager;
-import android.util.Log;
-import android.view.View;
-import android.view.View.OnClickListener;
-import android.webkit.WebView;
-import android.webkit.WebViewClient;
-import android.widget.Button;
-import android.widget.EditText;
-import android.widget.LinearLayout;
-import android.widget.ProgressBar;
-import android.widget.RadioButton;
-import android.widget.RelativeLayout;
-import android.widget.TextView;
-import android.widget.Toast;
-
-import org.iotivity.base.ModeType;
-import org.iotivity.base.OcException;
-import org.iotivity.base.OcPlatform;
-import org.iotivity.base.OcProvisioning;
-import org.iotivity.base.PlatformConfig;
-import org.iotivity.base.QualityOfService;
-import org.iotivity.base.ServiceType;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-
-
-public class LoginActivity extends Activity {
- private static final String TAG = "Easysetup Login: ";
-
- /* Samsung account */
- private WebView mWebView = null;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_login);
-
- /* For Samsung account authentifaction */
- mWebView = (WebView) findViewById(R.id.webView);
- mWebView.setVisibility(View.VISIBLE);
- mWebView.setInitialScale(200);
- mWebView.getSettings().setJavaScriptEnabled(true);
- //mWebView.getSettings().setSupportZoom(true);
- mWebView.getSettings().setBuiltInZoomControls(true);
- mWebView.setWebViewClient(new WebViewClientClass());
-
- mWebView.loadUrl("https://account.samsung.com/account/check.do?actionID=StartAP&serviceID=85o501t021&countryCode=KR&languageCode=ko&serviceChannel=PC_APP");
-
- }
-
- public void onDestroy() {
- super.onDestroy();
- }
-
- private class WebViewClientClass extends WebViewClient {
-
- @Override
- public void onPageFinished(WebView view, String url) {
- Log.e(TAG, "called!!! url=" + url);
-
- if(url.contains("https://account.samsung.com/account/hybridCommonClosed.do")){
-
- mWebView.setVisibility(View.INVISIBLE);
-
- //parsing url
- UrlQuerySanitizer sanitizer = new UrlQuerySanitizer();
- sanitizer.setAllowUnregisteredParamaters(true);
- sanitizer.parseUrl(url);
-
- String mAuthCode = null;
- mAuthCode = sanitizer.getValue("code");
-
- Intent intent = getIntent();
- intent.putExtra("authCode", mAuthCode);
- intent.putExtra("authProvider", "samsung");
-
- setResult(RESULT_OK, intent);
-
- finish();
- }
- }
- }
-}
+++ /dev/null
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical"
- android:id="@+id/loginlayout"
- tools:context="org.iotivity.service.easysetup.mediator.LoginActivity">
-
- <WebView
- android:id="@+id/webView"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:visibility="visible" />
-
-</LinearLayout>
+++ /dev/null
-<?xml version="1.0" encoding="utf-8"?>\r
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"\r
- android:orientation="vertical" android:layout_width="match_parent"\r
- android:layout_height="match_parent"\r
- android:baselineAligned="true"\r
- android:weightSum="1"\r
- android:nestedScrollingEnabled="false">\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content">\r
-\r
- <Button\r
- android:layout_width="wrap_content"\r
- android:layout_height="wrap_content"\r
- android:text="Discovery"\r
- android:id="@+id/btn_discoverResource"\r
- android:layout_marginLeft="20dp"\r
- android:layout_marginTop="10dp" />\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="match_parent"\r
- android:weightSum="1"\r
- android:baselineAligned="true"\r
- android:layout_marginLeft="20dp"\r
- android:id="@+id/layout_Security"\r
- android:layout_marginRight="20dp">\r
-\r
- <TextView\r
- android:layout_width="wrap_content"\r
- android:layout_height="wrap_content"\r
- android:text="@string/security_mode"\r
- android:id="@+id/text_EnableSecurity"\r
- android:phoneNumber="false"\r
- android:textSize="16sp"\r
- android:layout_marginTop="10dp"\r
- android:layout_marginLeft="20dp" />\r
-\r
- <ToggleButton\r
- android:layout_width="wrap_content"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/btn_Security"\r
- android:layout_marginLeft="40dp"\r
- android:layout_weight="0"\r
- android:textOff="Disable"\r
- android:textOn="Enable"\r
- android:layout_marginTop="10dp" />\r
-\r
- </LinearLayout>\r
-\r
- </LinearLayout>\r
-\r
- <View\r
- android:layout_height="2dip"\r
- android:background="#FF909090"\r
- android:layout_marginTop="10dp"\r
- android:layout_marginBottom="10dp"\r
- android:layout_marginLeft="15dp"\r
- android:layout_marginRight="15dp"\r
- android:layout_width="match_parent" />\r
-\r
- <LinearLayout\r
- android:orientation="vertical"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/layout_Excution"\r
- android:layout_marginLeft="10dp"\r
- android:layout_marginRight="10dp">\r
-\r
- <TextView\r
- android:layout_width="wrap_content"\r
- android:layout_height="wrap_content"\r
- android:text="@string/easysetup_sequence"\r
- android:id="@+id/textView22"\r
- android:layout_marginLeft="10dp"\r
- android:textSize="16sp" />\r
-\r
- <RadioGroup\r
- android:layout_width="match_parent"\r
- android:layout_height="match_parent"\r
- android:layout_marginTop="5dp"\r
- android:id="@+id/rg_EasysetupProcess"\r
- android:layout_marginLeft="20dp">\r
-\r
- <RadioButton\r
- android:layout_width="160dp"\r
- android:layout_height="32dp"\r
- android:text="@string/securityprovisioning"\r
- android:id="@+id/btn_configurSec"\r
- android:checked="false"\r
- android:textSize="12sp" />\r
-\r
- <RadioButton\r
- android:layout_width="160dp"\r
- android:layout_height="32dp"\r
- android:text="GetConfiguration"\r
- android:id="@+id/btn_getConfiguration"\r
- android:checked="false"\r
- android:textSize="12sp" />\r
-\r
- <RadioButton\r
- android:layout_width="173dp"\r
- android:layout_height="32dp"\r
- android:text="ProvisionDeviceConfig"\r
- android:id="@+id/btn_provisionDevConf"\r
- android:textSize="12sp" />\r
-\r
- <RadioButton\r
- android:layout_width="160dp"\r
- android:layout_height="32dp"\r
- android:text="@string/cloudprovisioning"\r
- android:id="@+id/btn_provisionCloudConf"\r
- android:textSize="12sp" />\r
- </RadioGroup>\r
-\r
- </LinearLayout>\r
-\r
- <View\r
- android:layout_height="2dip"\r
- android:background="#FF909090"\r
- android:layout_marginTop="10dp"\r
- android:layout_marginBottom="10dp"\r
- android:layout_marginLeft="15dp"\r
- android:layout_marginRight="15dp"\r
- android:layout_width="match_parent" />\r
-\r
- <ScrollView\r
- android:layout_width="fill_parent"\r
- android:layout_height="fill_parent"\r
- android:id="@+id/scrollView" >\r
-\r
- <LinearLayout\r
- android:orientation="vertical"\r
- android:layout_width="match_parent"\r
- android:layout_height="match_parent"\r
- android:id="@+id/layout_Infomation"\r
- android:gravity="center_horizontal"\r
- android:weightSum="1">\r
-\r
- <LinearLayout\r
- android:orientation="vertical"\r
- android:layout_width="match_parent"\r
- android:layout_height="match_parent"\r
- android:layout_marginLeft="20dp"\r
- android:layout_marginRight="20dp"\r
- android:id="@+id/layout_ConfigurSec"\r
- android:layout_marginTop="10dp"\r
- android:weightSum="1"\r
- android:visibility="gone">\r
-\r
- <TextView\r
- android:layout_width="wrap_content"\r
- android:layout_height="wrap_content"\r
- android:textAppearance="?android:attr/textAppearanceSmall"\r
- android:text="@string/security_provisioning_state"\r
- android:id="@+id/textView10" />\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/layout_secState"\r
- android:weightSum="1"\r
- android:layout_marginLeft="10dp"\r
- android:layout_marginTop="10dp" >\r
-\r
- <TextView\r
- android:layout_width="80dp"\r
- android:layout_height="wrap_content"\r
- android:text="State"\r
- android:id="@+id/textView12"\r
- android:layout_gravity="center_vertical" />\r
-\r
- <TextView\r
- android:layout_width="wrap_content"\r
- android:layout_height="wrap_content"\r
- android:text="empty"\r
- android:id="@+id/txt_secState" />\r
-\r
- </LinearLayout>\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/linearLayout2"\r
- android:weightSum="1"\r
- android:layout_marginLeft="10dp"\r
- android:layout_marginTop="10dp" >\r
-\r
- <TextView\r
- android:layout_width="80dp"\r
- android:layout_height="wrap_content"\r
- android:text="Device ID"\r
- android:id="@+id/textView"\r
- android:layout_gravity="center_vertical" />\r
-\r
- <TextView\r
- android:layout_width="wrap_content"\r
- android:layout_height="wrap_content"\r
- android:text="empty"\r
- android:id="@+id/txt_secDevID" />\r
- </LinearLayout>\r
-\r
- <FrameLayout\r
- android:layout_width="match_parent"\r
- android:layout_height="82dp"\r
- android:layout_weight="0.64"></FrameLayout>\r
-\r
- <Button\r
- android:layout_width="90dp"\r
- android:layout_height="wrap_content"\r
- android:text="START"\r
- android:id="@+id/btn_startConfigureSec"\r
- android:layout_marginTop="10dp"\r
- android:layout_gravity="bottom|right" />\r
-\r
- </LinearLayout>\r
-\r
- <LinearLayout\r
- android:orientation="vertical"\r
- android:layout_width="match_parent"\r
- android:layout_height="match_parent"\r
- android:layout_marginLeft="20dp"\r
- android:layout_marginRight="20dp"\r
- android:id="@+id/layout_GetConfiguration"\r
- android:layout_marginTop="10dp"\r
- android:visibility="gone">\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content">\r
-\r
- <TextView\r
- android:layout_width="wrap_content"\r
- android:layout_height="wrap_content"\r
- android:textAppearance="?android:attr/textAppearanceSmall"\r
- android:text="@string/enrollee_property_data"\r
- android:id="@+id/textView4" />\r
-\r
- <TextView\r
- android:layout_width="wrap_content"\r
- android:layout_height="wrap_content"\r
- android:text="state : "\r
- android:id="@+id/textView18"\r
- android:layout_marginLeft="80dp" />\r
-\r
- <TextView\r
- android:layout_width="wrap_content"\r
- android:layout_height="wrap_content"\r
- android:text="wait"\r
- android:id="@+id/txt_getConfigurationState" />\r
- </LinearLayout>\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/layout_devName"\r
- android:weightSum="1"\r
- android:layout_marginLeft="10dp"\r
- android:layout_marginTop="10dp" >\r
-\r
- <TextView\r
- android:layout_width="130dp"\r
- android:layout_height="wrap_content"\r
- android:text="devName"\r
- android:id="@+id/textView7"\r
- android:layout_gravity="center_vertical" />\r
-\r
- <TextView\r
- android:layout_width="wrap_content"\r
- android:layout_height="wrap_content"\r
- android:text="empty"\r
- android:id="@+id/txt_devName" />\r
-\r
- </LinearLayout>\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/layout_modelNumber"\r
- android:weightSum="1"\r
- android:layout_marginLeft="10dp"\r
- android:layout_marginTop="10dp" >\r
-\r
- <TextView\r
- android:layout_width="130dp"\r
- android:layout_height="wrap_content"\r
- android:text="modelNumber"\r
- android:id="@+id/textView7"\r
- android:layout_gravity="center_vertical" />\r
-\r
- <TextView\r
- android:layout_width="wrap_content"\r
- android:layout_height="wrap_content"\r
- android:text="empty"\r
- android:id="@+id/txt_modelNumber" />\r
-\r
- </LinearLayout>\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/layout_devType"\r
- android:weightSum="1"\r
- android:layout_marginLeft="10dp"\r
- android:layout_marginTop="10dp" >\r
-\r
- <TextView\r
- android:layout_width="130dp"\r
- android:layout_height="wrap_content"\r
- android:text="devType"\r
- android:id="@+id/textView8"\r
- android:layout_gravity="center_vertical" />\r
-\r
- <TextView\r
- android:layout_width="wrap_content"\r
- android:layout_height="wrap_content"\r
- android:text="empty"\r
- android:id="@+id/txt_devType" />\r
-\r
- </LinearLayout>\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/layout_devSubType"\r
- android:weightSum="1"\r
- android:layout_marginLeft="10dp"\r
- android:layout_marginTop="10dp" >\r
-\r
- <TextView\r
- android:layout_width="130dp"\r
- android:layout_height="wrap_content"\r
- android:text="devSubType"\r
- android:id="@+id/textView9"\r
- android:layout_gravity="center_vertical" />\r
-\r
- <TextView\r
- android:layout_width="wrap_content"\r
- android:layout_height="wrap_content"\r
- android:text="empty"\r
- android:id="@+id/txt_devSubType" />\r
-\r
- </LinearLayout>\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/layout_wifimode"\r
- android:weightSum="1"\r
- android:layout_marginLeft="10dp"\r
- android:layout_marginTop="10dp" >\r
-\r
- <TextView\r
- android:layout_width="130dp"\r
- android:layout_height="wrap_content"\r
- android:text="wifi mode"\r
- android:id="@+id/textView20"\r
- android:layout_gravity="center_vertical" />\r
-\r
- <TextView\r
- android:layout_width="wrap_content"\r
- android:layout_height="wrap_content"\r
- android:text="empty"\r
- android:id="@+id/txt_wifiMode" />\r
-\r
- </LinearLayout>\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/layout_wififreq"\r
- android:weightSum="1"\r
- android:layout_marginLeft="10dp"\r
- android:layout_marginTop="10dp" >\r
-\r
- <TextView\r
- android:layout_width="130dp"\r
- android:layout_height="wrap_content"\r
- android:text="wifi freq"\r
- android:id="@+id/textView21"\r
- android:layout_gravity="center_vertical" />\r
-\r
- <TextView\r
- android:layout_width="wrap_content"\r
- android:layout_height="wrap_content"\r
- android:text="empty"\r
- android:id="@+id/txt_wifiFreq" />\r
-\r
- </LinearLayout>\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/layout_coludAccessAble"\r
- android:weightSum="1"\r
- android:layout_marginLeft="10dp"\r
- android:layout_marginTop="10dp" >\r
-\r
- <TextView\r
- android:layout_width="130dp"\r
- android:layout_height="wrap_content"\r
- android:text="CloudAccessable"\r
- android:id="@+id/textView14"\r
- android:layout_gravity="center_vertical" />\r
-\r
- <TextView\r
- android:layout_width="wrap_content"\r
- android:layout_height="wrap_content"\r
- android:text="empty"\r
- android:id="@+id/txt_cloudAccessable" />\r
-\r
- </LinearLayout>\r
-\r
- <Button\r
- android:layout_width="90dp"\r
- android:layout_height="wrap_content"\r
- android:text="@string/start"\r
- android:id="@+id/btn_startGetConfiguration"\r
- android:layout_gravity="bottom|right" />\r
-\r
- </LinearLayout>\r
-\r
- <LinearLayout\r
- android:orientation="vertical"\r
- android:layout_width="match_parent"\r
- android:layout_height="match_parent"\r
- android:layout_marginLeft="20dp"\r
- android:layout_marginRight="20dp"\r
- android:id="@+id/layout_ProvisionDevConf"\r
- android:layout_marginTop="10dp"\r
- android:visibility="gone">\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content">\r
-\r
- <TextView\r
- android:layout_width="wrap_content"\r
- android:layout_height="wrap_content"\r
- android:textAppearance="?android:attr/textAppearanceSmall"\r
- android:text="@string/enroller_infomation"\r
- android:id="@+id/textView_DataProvisioning" />\r
-\r
- <TextView\r
- android:layout_width="wrap_content"\r
- android:layout_height="wrap_content"\r
- android:text="state : "\r
- android:id="@+id/textView19"\r
- android:layout_marginLeft="80dp" />\r
-\r
- <TextView\r
- android:layout_width="wrap_content"\r
- android:layout_height="wrap_content"\r
- android:text="wait"\r
- android:id="@+id/txt_provisionDevConfState" />\r
- </LinearLayout>\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/linearLayout3"\r
- android:weightSum="1"\r
- android:layout_marginLeft="10dp"\r
- android:layout_marginTop="10dp" >\r
-\r
- <TextView\r
- android:layout_width="130dp"\r
- android:layout_height="wrap_content"\r
- android:text="language"\r
- android:id="@+id/textView2"\r
- android:layout_gravity="center_vertical" />\r
-\r
- <EditText\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/editText_Language"\r
- android:layout_marginLeft="20dp"\r
- android:layout_gravity="center_vertical"\r
- android:text="korean" />\r
- </LinearLayout>\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/linearLayout4"\r
- android:weightSum="1"\r
- android:layout_marginLeft="10dp"\r
- android:layout_marginTop="10dp" >\r
-\r
- <TextView\r
- android:layout_width="130dp"\r
- android:layout_height="wrap_content"\r
- android:text="country"\r
- android:id="@+id/textView6"\r
- android:layout_gravity="center_vertical" />\r
-\r
- <EditText\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/editText_Country"\r
- android:layout_marginLeft="20dp"\r
- android:layout_gravity="center_vertical"\r
- android:text="korea" />\r
- </LinearLayout>\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/layout_InputLocation"\r
- android:weightSum="1"\r
- android:layout_marginLeft="10dp"\r
- android:layout_marginTop="10dp" >\r
-\r
- <TextView\r
- android:layout_width="130dp"\r
- android:layout_height="wrap_content"\r
- android:text="location"\r
- android:id="@+id/textView23"\r
- android:layout_gravity="center_vertical" />\r
-\r
- <EditText\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/editText_Location"\r
- android:text="Test_Location"\r
- android:layout_marginLeft="20dp"\r
- android:layout_gravity="center_vertical" />\r
- </LinearLayout>\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/layout_EnrollerSSID"\r
- android:weightSum="1"\r
- android:layout_marginLeft="10dp"\r
- android:layout_marginTop="10dp">\r
-\r
- <TextView\r
- android:layout_width="130dp"\r
- android:layout_height="wrap_content"\r
- android:text="@string/enroller_ssid"\r
- android:id="@+id/txt_ssid"\r
- android:layout_gravity="center_vertical" />\r
-\r
- <EditText\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/editText_EnrollerSSID"\r
- android:layout_marginLeft="20dp"\r
- android:layout_gravity="center_vertical"\r
- android:text="SSID" />\r
- </LinearLayout>\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/layout_EnrollerPW"\r
- android:weightSum="1"\r
- android:layout_marginLeft="10dp"\r
- android:layout_marginTop="10dp" >\r
-\r
- <TextView\r
- android:layout_width="130dp"\r
- android:layout_height="wrap_content"\r
- android:text="Enter Enroller's PW"\r
- android:id="@+id/txt_pass"\r
- android:layout_gravity="center_vertical" />\r
-\r
- <EditText\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/editText_EnrollerPW"\r
- android:layout_marginLeft="20dp"\r
- android:layout_gravity="center_vertical"\r
- android:text="PW" />\r
- </LinearLayout>\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/layout_DiscoveryChannel"\r
- android:weightSum="1"\r
- android:layout_marginLeft="10dp"\r
- android:layout_marginTop="10dp" >\r
-\r
- <TextView\r
- android:layout_width="130dp"\r
- android:layout_height="wrap_content"\r
- android:text="Enter Discovery Ch."\r
- android:id="@+id/textView11"\r
- android:layout_gravity="center_vertical" />\r
-\r
- <EditText\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/editText_DiscoveryChannel"\r
- android:layout_marginLeft="20dp"\r
- android:layout_gravity="center_vertical"\r
- android:text="1" />\r
- </LinearLayout>\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/layout_LocationAddr"\r
- android:weightSum="1"\r
- android:layout_marginLeft="10dp"\r
- android:layout_marginTop="10dp" >\r
-\r
- <TextView\r
- android:layout_width="130dp"\r
- android:layout_height="wrap_content"\r
- android:text="Enter Addr"\r
- android:id="@+id/textView11"\r
- android:layout_gravity="center_vertical" />\r
-\r
- <EditText\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/editText_LocationAddr"\r
- android:layout_marginLeft="20dp"\r
- android:layout_gravity="center_vertical"\r
- android:text="addr=Seoul, Rep. of Korea" />\r
- </LinearLayout>\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/layout_LocationZip"\r
- android:weightSum="1"\r
- android:layout_marginLeft="10dp"\r
- android:layout_marginTop="10dp" >\r
-\r
- <TextView\r
- android:layout_width="130dp"\r
- android:layout_height="wrap_content"\r
- android:text="Enter Zip code"\r
- android:id="@+id/textView11"\r
- android:layout_gravity="center_vertical" />\r
-\r
- <EditText\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/editText_LocationZip"\r
- android:layout_marginLeft="20dp"\r
- android:layout_gravity="center_vertical"\r
- android:text="zip=02848" />\r
- </LinearLayout>\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/layout_LocationBuilding"\r
- android:weightSum="1"\r
- android:layout_marginLeft="10dp"\r
- android:layout_marginTop="10dp" >\r
-\r
- <TextView\r
- android:layout_width="130dp"\r
- android:layout_height="wrap_content"\r
- android:text="Enter Building name"\r
- android:id="@+id/textView11"\r
- android:layout_gravity="center_vertical" />\r
-\r
- <EditText\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/editText_LocationBuilding"\r
- android:layout_marginLeft="20dp"\r
- android:layout_gravity="center_vertical"\r
- android:text="bd=apartment" />\r
- </LinearLayout>\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/layout_EnrollerAuthType"\r
- android:weightSum="1"\r
- android:layout_marginLeft="10dp"\r
- android:layout_marginTop="10dp" >\r
-\r
- <TextView\r
- android:layout_width="130dp"\r
- android:layout_height="wrap_content"\r
- android:text="@string/select_enroller_authentication_type"\r
- android:id="@+id/txt_authtype"\r
- android:layout_gravity="center_vertical" />\r
-\r
- <Spinner\r
- android:layout_width="fill_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/spinner_authType"\r
- android:layout_marginLeft="20dp"\r
- android:layout_gravity="center_vertical"\r
- android:spinnerMode="dropdown" />\r
-\r
- </LinearLayout>\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/layout_EnrollerEncType"\r
- android:weightSum="1"\r
- android:layout_marginLeft="10dp"\r
- android:layout_marginTop="10dp" >\r
-\r
- <TextView\r
- android:layout_width="130dp"\r
- android:layout_height="wrap_content"\r
- android:text="@string/select_enroller_encription_type"\r
- android:id="@+id/textView5"\r
- android:layout_gravity="center_vertical" />\r
-\r
- <Spinner\r
- android:layout_width="fill_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/spinner_encType"\r
- android:layout_marginLeft="20dp"\r
- android:layout_gravity="center_vertical"\r
- android:spinnerMode="dropdown" />\r
-\r
- </LinearLayout>\r
-\r
- <Button\r
- android:layout_width="90dp"\r
- android:layout_height="wrap_content"\r
- android:text="START"\r
- android:id="@+id/btn_startProvisionDevConf"\r
- android:layout_marginTop="10dp"\r
- android:layout_gravity="bottom|right" />\r
-\r
- </LinearLayout>\r
-\r
- <LinearLayout\r
- android:orientation="vertical"\r
- android:layout_width="match_parent"\r
- android:layout_height="match_parent"\r
- android:layout_marginLeft="20dp"\r
- android:layout_marginRight="20dp"\r
- android:id="@+id/layout_ProvisionCloudConf"\r
- android:layout_marginTop="10dp"\r
- android:visibility="gone">\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content">\r
-\r
- <TextView\r
- android:layout_width="wrap_content"\r
- android:layout_height="wrap_content"\r
- android:textAppearance="?android:attr/textAppearanceSmall"\r
- android:text="Cloud Information"\r
- android:id="@+id/textView15" />\r
-\r
- <TextView\r
- android:layout_width="wrap_content"\r
- android:layout_height="wrap_content"\r
- android:text="state : "\r
- android:id="@+id/textView24"\r
- android:layout_marginLeft="80dp" />\r
-\r
- <TextView\r
- android:layout_width="wrap_content"\r
- android:layout_height="wrap_content"\r
- android:text="wait"\r
- android:id="@+id/txt_provisionCloudConfState" />\r
- </LinearLayout>\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/linearLayout11"\r
- android:weightSum="1"\r
- android:layout_marginLeft="10dp"\r
- android:layout_marginTop="10dp" >\r
-\r
- <TextView\r
- android:layout_width="130dp"\r
- android:layout_height="wrap_content"\r
- android:text="Enter Target Cloud's Authcode"\r
- android:id="@+id/textView16"\r
- android:layout_gravity="center_vertical" />\r
-\r
- <EditText\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/editText_authcode"\r
- android:layout_marginLeft="20dp"\r
- android:layout_gravity="center_vertical"\r
- android:text="authcode" />\r
- </LinearLayout>\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/linearLayout12"\r
- android:weightSum="1"\r
- android:layout_marginLeft="10dp"\r
- android:layout_marginTop="10dp" >\r
-\r
- <TextView\r
- android:layout_width="130dp"\r
- android:layout_height="wrap_content"\r
- android:text="Enter Target Cloud's AuthProvider"\r
- android:id="@+id/textView17"\r
- android:layout_gravity="center_vertical" />\r
-\r
- <EditText\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/editText_authprovider"\r
- android:layout_marginLeft="20dp"\r
- android:layout_gravity="center_vertical"\r
- android:text="authprovider" />\r
- </LinearLayout>\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/linearLayout"\r
- android:weightSum="1"\r
- android:layout_marginLeft="10dp"\r
- android:layout_marginTop="10dp" >\r
-\r
- <TextView\r
- android:layout_width="130dp"\r
- android:layout_height="wrap_content"\r
- android:text="Enter Target Cloud's Interface server"\r
- android:id="@+id/textView3"\r
- android:layout_gravity="center_vertical" />\r
-\r
- <EditText\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/editText_ciserver"\r
- android:layout_marginLeft="20dp"\r
- android:layout_gravity="center_vertical"\r
- android:text="ciserver" />\r
- </LinearLayout>\r
-\r
- <Button\r
- android:layout_width="90dp"\r
- android:layout_height="wrap_content"\r
- android:text="START"\r
- android:id="@+id/btn_startProvisionCloudConf"\r
- android:layout_marginTop="10dp"\r
- android:layout_gravity="bottom|right" />\r
-\r
- </LinearLayout>\r
- </LinearLayout>\r
- </ScrollView>\r
-\r
-</LinearLayout>
\ No newline at end of file
+++ /dev/null
-<menu xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:app="http://schemas.android.com/apk/res-auto"
- xmlns:tools="http://schemas.android.com/tools"
- tools:context="org.iotivity.service.easysetup.MainActivity" >
-
- <item
- android:id="@+id/action_settings"
- android:orderInCategory="100"
- android:title="@string/action_settings"/>
-
-</menu>
+++ /dev/null
-<?xml version="1.0" encoding="utf-8"?>\r
-<resources>\r
- <string-array name="auth_type">\r
- <item>NONE_AUTH</item>\r
- <item>WEP</item>\r
- <item>WPA_PSK</item>\r
- <item>WPA2_PSK</item>\r
- </string-array>\r
- <string-array name="enc_type">\r
- <item>NONE_ENC</item>\r
- <item>WEP_64</item>\r
- <item>WEP_128</item>\r
- <item>TKIP</item>\r
- <item>AES</item>\r
- <item>TKIP_AES</item>\r
- </string-array>\r
-</resources>
\ No newline at end of file
+++ /dev/null
-<resources>
-
- <!-- Default screen margins, per the Android Design guidelines. -->
- <dimen name="activity_horizontal_margin">16dp</dimen>
- <dimen name="activity_vertical_margin">1dp</dimen>
-
-</resources>
+++ /dev/null
-<?xml version="1.0" encoding="utf-8"?>
-<resources>
- <string name="app_name">Easy Setup</string>
- <string name="action_settings">Settings</string>
-
- <string name="security_mode">Security Mode</string>
- <string name="enroller_ssid">Enter Enroller\'s SSID</string>
- <string name="select_enroller_authentication_type">Select Enroller\'s Authentication Type</string>
- <string name="select_enroller_encription_type">Select Enroller\'s Encription Type</string>
- <string name="enroller_infomation">Enroller\'s Infomation</string>
- <string name="requsetpropertydata">RequsetPropertyData</string>
- <string name="securityprovisioning">SecurityProvisioning</string>
- <string name="dataprovisioning">DataProvisioning</string>
- <string name="cloudprovisioning">CloudProvisioning</string>
- <string name="log">log</string>
- <string name="start">START</string>
- <string name="enrollee_property_data">Enrollee\'s Property Data</string>
- <string name="enter_enroller_apos_s_pw">Enter Enroller\'s PW</string>
- <string name="easysetup_sequence">Easysetup Sequence</string>
- <string name="security_provisioning_state">Security Provisioning State</string>
-
-
-</resources>
+++ /dev/null
-<resources>
-
- <!--
- Base application theme, dependent on API level. This theme is replaced
- by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
- -->
- <style name="AppBaseTheme" parent="android:Theme.Light">
- <!--
- Theme customizations available in newer API levels can go in
- res/values-vXX/styles.xml, while customizations related to
- backward-compatibility can go here.
- -->
- </style>
-
- <!-- Application theme. -->
- <style name="AppTheme" parent="AppBaseTheme">
- <!-- All customizations that are NOT specific to a particular API-level can go here. -->
- </style>
-
-</resources>
+++ /dev/null
-//******************************************************************\r
-//\r
-// Copyright 2016 Samsung Electronics All Rights Reserved.\r
-//\r
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
-//\r
-// Licensed under the Apache License, Version 2.0 (the "License");\r
-// you may not use this file except in compliance with the License.\r
-// You may obtain a copy of the License at\r
-//\r
-// http://www.apache.org/licenses/LICENSE-2.0\r
-//\r
-// Unless required by applicable law or agreed to in writing, software\r
-// distributed under the License is distributed on an "AS IS" BASIS,\r
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-// See the License for the specific language governing permissions and\r
-// limitations under the License.\r
-//\r
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
-\r
-// Top-level build file where you can add configuration options common to all sub-projects/modules.\r
-\r
-buildscript {\r
- repositories {\r
- jcenter()\r
- }\r
- dependencies {\r
- classpath 'com.android.tools.build:gradle:1.3.0'\r
-\r
- // NOTE: Do not place your application dependencies here; they belong\r
- // in the individual module build.gradle files\r
- }\r
-}\r
-\r
-allprojects {\r
- repositories {\r
- jcenter()\r
- }\r
-}\r
+++ /dev/null
-#
-# //******************************************************************
-# //
-# // Copyright 2016 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.
-# //
-# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#
-
-# Project-wide Gradle settings.
-
-# IDE (e.g. Android Studio) users:
-# Gradle settings configured through the IDE *will override*
-# any settings specified in this file.
-
-# For more details on how to configure your build environment visit
-# http://www.gradle.org/docs/current/userguide/build_environment.html
-
-# Specifies the JVM arguments used for the daemon process.
-# The setting is particularly useful for tweaking memory settings.
-# Default value: -Xmx10248m -XX:MaxPermSize=256m
-# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
-
-# When configured, Gradle will run in incubating parallel mode.
-# This option should only be used with decoupled projects. More details, visit
-# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
-# org.gradle.parallel=true
-TARGET_ARCH=armeabi
-RELEASE=release
-SECURED=1
-ERROR_MSG="if building examples from android-studio, you might need to modify the default TARGET_ARCH\
- and RELEASE in <iotivity>/android/examples/gradle.properties,\
- if your aar file has different values for TARGET_ARCH and RELEASE"
-
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2016 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 ':app'
+++ /dev/null
-#//******************************************************************
-#//
-#// Copyright 2016 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.
-#//
-#//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-import os
-import platform
-Import('env')
-
-android_home = env.get('ANDROID_HOME')
-
-ANDROID_TARGET_ARCH = env.get('TARGET_ARCH')
-if env.get('RELEASE'):
- ANDROID_RELEASE="release"
-else:
- ANDROID_RELEASE="debug"
-
-os.environ['ANDROID_HOME'] = env.get('ANDROID_HOME')
-os.environ['ANDROID_NDK_HOME'] = env.get('ANDROID_NDK')
-
-if not os.path.exists(android_home + '/platforms/android-21') or not os.path.exists(android_home + '/build-tools/20.0.0'):
- print '''
-***************************************** Info ********************************
-* Either 'Android API 21' is not installed or 'Android SDK Build Tools *
-* 20.0.0' is not installed. The Android SDK Manager will now open. Please *
-* be sure to deselect all options, then select the following 2 packages: *
-* 1. Under "Tools" select "Android SDK Build-tools" Revision 20. *
-* 2. Under "Android 5.0.1 (API 21)" select "SDK Platform" *
-* 3. Continue by selecting "Install 2 Packages" *
-* *
-* NOTE: If you have an http proxy, please press ctrl+c now and edit/create *
-* the following file in your $HOME directory as follows: *
-* *
-* Edit/Create file: "$HOME/.android/androidtool.cfg" *
-* *
-* http.proxyPort=<YOUR_PORT_NUMBER> *
-* sdkman.monitor.density=108 *
-* http.proxyHost=<YOUR_HTTP_PROXY_ADDRESS> *
-* sdkman.show.update.only=true *
-* sdkman.ask.adb.restart=false *
-* sdkman.force.http=true *
-* sdkman.show.updateonly=true *
-* *
-*******************************************************************************
-
-...Opening Android SDK Manager now. Once you are finished, the build will continue.
-'''
- os.system(android_home + '/tools/android')
-
-#SConscript("../../../../../../android/android_api/SConscript")
-
-def ensure_libs(target, source, env):
- return target, [source, env.get('BUILD_DIR') + 'liboc.so', env.get('BUILD_DIR') + 'liboc_logger.so']
-
-jdk_env = Environment(ENV=os.environ)
-jdk_env['BUILDERS']['Gradle'] = Builder(action = env.get('ANDROID_GRADLE') +
- ' build -bservice/easy-setup/sampleapp/mediator/android-samsung/EasySetup/build.gradle -PTARGET_ARCH=%s -PRELEASE=%s --stacktrace' %(ANDROID_TARGET_ARCH, ANDROID_RELEASE),
- emitter = ensure_libs)
-jdk_env['BUILD_DIR'] = env.get('BUILD_DIR')
-cmdBuildEasysetupSCApp=jdk_env.Gradle(target="EasySetup/app/apk",
- source="EasySetup/app/src/main/java/org/iotivity/service/easysetup/EasysetupActivity.java")
-
-Depends(cmdBuildEasysetupSCApp, env.get('baseAAR'))
\ No newline at end of file
+++ /dev/null
-#built application files\r
-*.apk\r
-*.ap_\r
-\r
-# files for the dex VM\r
-*.dex\r
-\r
-# Java class files\r
-*.class\r
-\r
-# generated files\r
-bin/\r
-gen/\r
-\r
-# Local configuration file (sdk path, etc)\r
-local.properties\r
-\r
-# Proguard folder generated by Eclipse \r
-proguard/ \r
-\r
-# Windows thumbnail db\r
-Thumbs.db\r
-\r
-# OSX files\r
-.DS_Store\r
-\r
-# Eclipse project files\r
-.classpath\r
-.project\r
-\r
-#Android Studio & Gradle\r
-.gradle\r
-/local.properties\r
-/.idea/workspace.xml\r
-/.idea/libraries\r
-.DS_Store\r
-/build/*\r
-/base/build/*\r
-/base/obj/*\r
-/base/libs/*\r
-/sample/*\r
-\r
-#Some older projects\r
-/*/out\r
-/*/*/build\r
-/*/*/production\r
-*.iws\r
-*.ipr\r
-*~\r
-*.swp
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>\r
-<module external.linked.project.id="EasySetup" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$" external.system.id="GRADLE" external.system.module.group="" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">\r
- <component name="FacetManager">\r
- <facet type="java-gradle" name="Java-Gradle">\r
- <configuration>\r
- <option name="BUILD_FOLDER_PATH" value="$MODULE_DIR$/build" />\r
- <option name="BUILDABLE" value="false" />\r
- </configuration>\r
- </facet>\r
- </component>\r
- <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_7" inherit-compiler-output="true">\r
- <exclude-output />\r
- <content url="file://$MODULE_DIR$">\r
- <excludeFolder url="file://$MODULE_DIR$/.gradle" />\r
- </content>\r
- <orderEntry type="inheritedJdk" />\r
- <orderEntry type="sourceFolder" forTests="false" />\r
- </component>\r
-</module>\r
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<module external.linked.project.id="EasySetupGradle" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$" external.system.id="GRADLE" external.system.module.group="" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
- <component name="FacetManager">
- <facet type="java-gradle" name="Java-Gradle">
- <configuration>
- <option name="BUILD_FOLDER_PATH" value="$MODULE_DIR$/build" />
- <option name="BUILDABLE" value="false" />
- </configuration>
- </facet>
- </component>
- <component name="NewModuleRootManager" inherit-compiler-output="true">
- <exclude-output />
- <content url="file://$MODULE_DIR$">
- <excludeFolder url="file://$MODULE_DIR$/.gradle" />
- </content>
- <orderEntry type="inheritedJdk" />
- <orderEntry type="sourceFolder" forTests="false" />
- </component>
-</module>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<module external.linked.project.id=":app" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$/.." external.system.id="GRADLE" external.system.module.group="EasySetup" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
- <component name="FacetManager">
- <facet type="android-gradle" name="Android-Gradle">
- <configuration>
- <option name="GRADLE_PROJECT_PATH" value=":app" />
- </configuration>
- </facet>
- <facet type="android" name="Android">
- <configuration>
- <option name="SELECTED_BUILD_VARIANT" value="debug" />
- <option name="SELECTED_TEST_ARTIFACT" value="_android_test_" />
- <option name="ASSEMBLE_TASK_NAME" value="assembleDebug" />
- <option name="COMPILE_JAVA_TASK_NAME" value="compileDebugSources" />
- <option name="ASSEMBLE_TEST_TASK_NAME" value="assembleDebugAndroidTest" />
- <option name="COMPILE_JAVA_TEST_TASK_NAME" value="compileDebugAndroidTestSources" />
- <afterSyncTasks>
- <task>generateDebugAndroidTestSources</task>
- <task>generateDebugSources</task>
- </afterSyncTasks>
- <option name="ALLOW_USER_CONFIGURATION" value="false" />
- <option name="MANIFEST_FILE_RELATIVE_PATH" value="/src/main/AndroidManifest.xml" />
- <option name="RES_FOLDER_RELATIVE_PATH" value="/src/main/res" />
- <option name="RES_FOLDERS_RELATIVE_PATH" value="file://$MODULE_DIR$/src/main/res" />
- <option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" />
- </configuration>
- </facet>
- </component>
- <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_7" inherit-compiler-output="false">
- <output url="file://$MODULE_DIR$/build/intermediates/classes/debug" />
- <output-test url="file://$MODULE_DIR$/build/intermediates/classes/androidTest/debug" />
- <exclude-output />
- <content url="file://$MODULE_DIR$">
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/debug" isTestSource="false" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/debug" isTestSource="false" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/debug" isTestSource="false" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/debug" isTestSource="false" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/debug" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/debug" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/androidTest/debug" isTestSource="true" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/androidTest/debug" isTestSource="true" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/androidTest/debug" isTestSource="true" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/androidTest/debug" isTestSource="true" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/androidTest/debug" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/androidTest/debug" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/res" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/resources" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/assets" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/aidl" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/java" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/jni" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/rs" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/res" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/assets" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/aidl" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/jni" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/rs" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/res" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/resources" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/assets" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/aidl" isTestSource="true" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/java" isTestSource="true" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/jni" isTestSource="true" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/rs" isTestSource="true" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/assets" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/bundles" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/classes" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/coverage-instrumented-classes" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dependency-cache" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex-cache" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/exploded-aar/EasySetup/EasySetupCore-debug/unspecified/jars" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/exploded-aar/EasySetup/iotivity-armeabi-base-debug/unspecified/jars" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/jacoco" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/javaResources" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/libs" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/lint" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/manifests" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/ndk" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/pre-dexed" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/proguard" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/res" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/rs" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/symbols" />
- <excludeFolder url="file://$MODULE_DIR$/build/outputs" />
- <excludeFolder url="file://$MODULE_DIR$/build/tmp" />
- </content>
- <orderEntry type="jdk" jdkName="Android API 21 Platform" jdkType="Android SDK" />
- <orderEntry type="sourceFolder" forTests="false" />
- <orderEntry type="module" module-name="EasySetupCore-debug" exported="" />
- <orderEntry type="module" module-name="iotivity-armeabi-base-debug" exported="" />
- <orderEntry type="library" exported="" name="EasySetupCore-debug-unspecified" level="project" />
- <orderEntry type="library" exported="" name="iotivity-armeabi-base-debug-unspecified" level="project" />
- </component>
-</module>
\ No newline at end of file
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2016 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-apply plugin: 'com.android.application'
-
-android {
- compileSdkVersion 21
- buildToolsVersion "20.0.0"
-
- defaultConfig {
- applicationId "org.iotivity.service.easysetup"
- minSdkVersion 21
- targetSdkVersion 21
- versionCode 1
- versionName "1.0"
- }
- buildTypes {
- release {
- minifyEnabled false
- proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
- }
- }
- lintOptions {
- abortOnError false
- }
-}
-repositories {
- flatDir {
- dirs "../../../../../../../android/android_api/base/build/outputs/aar/", "../../../../../mediator/richsdk/android/EasySetupCore/build/outputs/aar/"
- }
-}
-
-try {
- dependencies {
- compile ":iotivity-base-${TARGET_ARCH}-${RELEASE}@aar"
- compile ":EasySetupCore-${RELEASE}@aar"
- }
-} catch (all) {
- print "${ERROR_MSG}"
- assert all
-}
+++ /dev/null
-# Add project specific ProGuard rules here.
-# By default, the flags in this file are appended to flags specified
-# in /home/rahul/sdk/tools/proguard/proguard-android.txt
-# You can edit the include path and order by changing the proguardFiles
-# directive in build.gradle.
-#
-# For more details, see
-# http://developer.android.com/guide/developing/tools/proguard.html
-
-# Add any project specific keep options here:
-
-# If your project uses WebView with JS, uncomment the following
-# and specify the fully qualified class name to the JavaScript interface
-# class:
-#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
-# public *;
-#}
+++ /dev/null
-<?xml version="1.0" encoding="utf-8"?>
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="org.iotivity.service.easysetup"
- android:versionCode="1"
- android:versionName="1.0">
-
- <uses-permission android:name="android.permission.INTERNET" />
- <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
- <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
- <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
- <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
-
- <uses-feature
- android:name="android.hardware.touchscreen"
- android:required="false" />
-
- <application
- android:allowBackup="true"
- android:icon="@drawable/ic_launcher"
- android:label="@string/app_name"
- android:theme="@style/AppTheme">
- <activity
- android:name=".LoginActivity"
- android:label="@string/app_name">
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- </intent-filter>
- </activity>
- <activity android:name=".EasysetupActivity" android:label="@string/app_name">
- <intent-filter>
- <action android:name="android.intent.action.MAIN"/>
- <category android:name="android.intent.category.LAUNCHER"/>
- </intent-filter>
- </activity>
- </application>
-
-</manifest>
+++ /dev/null
-{
- "acl": {
- "aclist": {
- "aces": [
- {
- "subjectuuid": "*",
- "resources": [
- {
- "href": "/oic/res",
- "rel": "",
- "rt": ["oic.wk.res"],
- "if": ["oic.if.ll"]
- },
- {
- "href": "/oic/d",
- "rel": "",
- "rt": ["oic.wk.d"],
- "if": ["oic.if.baseline", "oic.if.r"]
- },
- {
- "href": "/oic/p",
- "rel": "",
- "rt": ["oic.wk.p"],
- "if": ["oic.if.baseline", "oic.if.r"]
- }
- ],
- "permission": 2
- },
- {
- "subjectuuid": "*",
- "resources": [
- {
- "href": "/oic/sec/doxm",
- "rel": "",
- "rt": ["oic.r.doxm"],
- "if": ["oic.if.baseline"]
- },
- {
- "href": "/oic/sec/pstat",
- "rel": "",
- "rt": ["oic.r.pstat"],
- "if": ["oic.if.baseline"]
- }
- ],
- "permission": 2
- }
- ]
- },
- "rowneruuid" : "61646d69-6e44-6576-6963-655575696430"
- },
- "pstat": {
- "isop": true,
- "deviceuuid": "61646d69-6e44-6576-6963-655575696430",
- "rowneruuid": "61646d69-6e44-6576-6963-655575696430",
- "cm": 0,
- "tm": 0,
- "om": 4,
- "sm": 4
- },
- "doxm": {
- "oxms": [0],
- "oxmsel": 0,
- "sct": 1,
- "owned": true,
- "deviceuuid": "61646d69-6e44-6576-6963-655575696430",
- "devowneruuid": "61646d69-6e44-6576-6963-655575696430",
- "rowneruuid": "61646d69-6e44-6576-6963-655575696430"
- }
-}
+++ /dev/null
-/**
- * ***************************************************************
- * <p/>
- * Copyright 2016 Samsung Electronics All Rights Reserved.
- * <p/>
- * <p/>
- * <p/>
- * 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
- * <p/>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p/>
- * 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.
- * <p/>
- * ****************************************************************
- */
-
-package org.iotivity.service.easysetup;
-
-import android.app.Activity;
-import android.content.Context;
-import android.content.Intent;
-import android.content.SharedPreferences;
-import android.os.Bundle;
-import android.preference.PreferenceManager;
-import android.util.Log;
-import android.view.View;
-import android.widget.ArrayAdapter;
-import android.widget.Button;
-import android.widget.EditText;
-import android.widget.LinearLayout;
-import android.widget.RadioButton;
-import android.widget.RadioGroup;
-import android.widget.Spinner;
-import android.widget.TextView;
-import android.widget.Toast;
-import android.widget.ToggleButton;
-
-import org.iotivity.base.ErrorCode;
-import org.iotivity.base.ModeType;
-import org.iotivity.base.OcConnectivityType;
-import org.iotivity.base.OcException;
-import org.iotivity.base.OcHeaderOption;
-import org.iotivity.base.ObserveType;
-import org.iotivity.base.OcPlatform;
-import org.iotivity.base.OcPresenceStatus;
-import org.iotivity.base.OcProvisioning;
-import org.iotivity.base.OcRepresentation;
-import org.iotivity.base.OcResource;
-import org.iotivity.base.PlatformConfig;
-import org.iotivity.base.QualityOfService;
-import org.iotivity.base.ServiceType;
-import org.iotivity.base.OcAccountManager;
-import org.iotivity.service.easysetup.mediator.ESConstants;
-import org.iotivity.service.easysetup.mediator.CloudProp;
-import org.iotivity.service.easysetup.mediator.CloudPropProvisioningCallback;
-import org.iotivity.service.easysetup.mediator.CloudPropProvisioningStatus;
-import org.iotivity.service.easysetup.mediator.DeviceProp;
-import org.iotivity.service.easysetup.mediator.DevicePropProvisioningCallback;
-import org.iotivity.service.easysetup.mediator.DevicePropProvisioningStatus;
-import org.iotivity.service.easysetup.mediator.ESException;
-import org.iotivity.service.easysetup.mediator.EasySetup;
-import org.iotivity.service.easysetup.mediator.EnrolleeConf;
-import org.iotivity.service.easysetup.mediator.GetConfigurationCallback;
-import org.iotivity.service.easysetup.mediator.GetConfigurationStatus;
-import org.iotivity.service.easysetup.mediator.RemoteEnrollee;
-import org.iotivity.service.easysetup.mediator.SecurityProvisioningCallback;
-import org.iotivity.service.easysetup.mediator.SecurityProvisioningStatus;
-import org.iotivity.service.easysetup.mediator.enums.ESCloudProvState;
-import org.iotivity.service.easysetup.mediator.enums.ESResult;
-import org.iotivity.service.easysetup.mediator.enums.WIFI_AUTHTYPE;
-import org.iotivity.service.easysetup.mediator.enums.WIFI_ENCTYPE;
-import org.iotivity.service.easysetup.mediator.enums.WIFI_FREQ;
-import org.iotivity.service.easysetup.mediator.enums.WIFI_MODE;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.EnumSet;
-import java.util.HashMap;
-import java.util.List;
-
-
-public class EasysetupActivity extends Activity
- implements OcPlatform.OnPresenceListener,
- OcResource.OnObserveListener{
- private static final String TAG = "Easysetup Mediator: ";
- PlatformConfig cfg;
- OcAccountManager m_accountManager = null;
- final String deviceID = "9E09F4FE-978A-4BC3-B356-1F93BCA37829";
- final String CIServer = "coap+tcp://52.69.149.85:5683";
-
- private static final int BUFFER_SIZE = 1024;
-
- private String filePath = "";
- public static final String OIC_CLIENT_JSON_DB_FILE = "oic_svr_db_client.dat";
- public static final String OIC_SQL_DB_FILE = "PDM.db";
-
- private boolean isFirstTime = true;
-
- String mEnrolleeDeviceID;
- String mAuthCode;
- String mAuthProvider;
- String mRefreshtoken;
- String mUserID;
- String mAccessToken;
- String mEnrolleeAuthCode;
- byte[] mCertificate;
- int mCredID;
-
- ToggleButton mSecurityMode;
-
- RadioGroup mEasysetupProcess;
- RadioButton mConfigureSecProcess;
- RadioButton mGetConfigurationProcess;
- RadioButton mProvisionDevPropProcess;
- RadioButton mProvisionCloudPropProcess;
-
- Button mDiscoverResource;
- Button mStartGetConfiguration;
- Button mStartConfigureSec;
- Button mStartProvisionDevProp;
- Button mStartProvisionCloudProp;
-
- TextView mGetconfigurationStateText;
- TextView mDevNameText;
- TextView mModelNumberText;
- TextView mLanguageText;
- TextView mCountryText;
- TextView mWifiModeText;
- TextView mWifiFreqText;
- TextView mCloudAccessableText;
- TextView mSecStateText;
- TextView mSecDevIDText;
- TextView mProvisionDevPropState;
- TextView mProvisionCloudPropState;
-
- EditText mEnrollerSsidText;
- EditText mEnrollerPWText;
- EditText mInputLanguageText;
- EditText mInputCountryText;
- EditText mInputLocationText;
- EditText mAuthCodeText;
- EditText mAuthProviderText;
- EditText mCIServerText;
-
- LinearLayout mGetConfigurationInfo;
- LinearLayout mConfigureSecInfo;
- LinearLayout mProvisionDevPropInfo;
- LinearLayout mProvisionCloudPropInfo;
-
- Spinner mAuthType;
- Spinner mEncType;
-
- EasySetup mEasySetup;
- RemoteEnrollee mRemoteEnrollee;
-
- Activity mActivity;
- Context mContext;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.easysetup_main);
-
- mActivity = EasysetupActivity.this;
- mContext = mActivity.getBaseContext();
-
- mSecurityMode = (ToggleButton) findViewById(R.id.btn_Security);
-
- mEasysetupProcess = (RadioGroup) findViewById(R.id.rg_EasysetupProcess);
-
- mConfigureSecProcess = (RadioButton) findViewById(R.id.btn_configurSec);
- mGetConfigurationProcess = (RadioButton) findViewById(R.id.btn_getConfiguration);
- mProvisionDevPropProcess = (RadioButton) findViewById(R.id.btn_provisionDevConf);
- mProvisionCloudPropProcess =
- (RadioButton) findViewById(R.id.btn_provisionCloudConf);
-
- mDiscoverResource = (Button) findViewById(R.id.btn_discoverResource);
- mStartGetConfiguration =
- (Button) findViewById(R.id.btn_startGetConfiguration);
- mStartConfigureSec = (Button) findViewById(R.id.btn_startConfigureSec);
- mStartProvisionDevProp = (Button) findViewById(R.id.btn_startProvisionDevConf);
- mStartProvisionCloudProp = (Button) findViewById(R.id.btn_startProvisionCloudConf);
-
- mGetconfigurationStateText =
- (TextView) findViewById(R.id.txt_getConfigurationState);
- mDevNameText = (TextView) findViewById(R.id.txt_devName);
- mModelNumberText = (TextView) findViewById(R.id.txt_modelNumber);
- mLanguageText = (TextView) findViewById(R.id.txt_language);
- mCountryText = (TextView) findViewById(R.id.txt_country);
- mWifiModeText = (TextView) findViewById(R.id.txt_wifiMode);
- mWifiFreqText = (TextView) findViewById(R.id.txt_wifiFreq);
- mCloudAccessableText = (TextView) findViewById(R.id.txt_cloudAccessable);
- mSecStateText = (TextView) findViewById(R.id.txt_secState);
- mSecDevIDText = (TextView) findViewById(R.id.txt_secDevID);
- mProvisionDevPropState = (TextView) findViewById(R.id.txt_provisionDevConfState);
- mProvisionCloudPropState =
- (TextView) findViewById(R.id.txt_provisionCloudConfState);
-
- mEnrollerSsidText = (EditText) findViewById(R.id.editText_EnrollerSSID);
- mEnrollerPWText = (EditText) findViewById(R.id.editText_EnrollerPW);
- mInputLanguageText = (EditText) findViewById(R.id.editText_Language);
- mInputCountryText = (EditText) findViewById(R.id.editText_Country);
- mInputLocationText = (EditText) findViewById(R.id.editText_Location);
- mAuthCodeText = (EditText) findViewById(R.id.editText_authcode);
- mAuthProviderText = (EditText) findViewById(R.id.editText_authprovider);
- mCIServerText = (EditText) findViewById(R.id.editText_ciserver);
-
- mGetConfigurationInfo =
- (LinearLayout) findViewById(R.id.layout_GetConfiguration);
- mConfigureSecInfo = (LinearLayout) findViewById(R.id.layout_ConfigurSec);
- mProvisionDevPropInfo = (LinearLayout) findViewById(R.id.layout_ProvisionDevConf);
- mProvisionCloudPropInfo = (LinearLayout) findViewById(R.id.layout_ProvisionCloudConf);
-
- mAuthType = (Spinner) findViewById(R.id.spinner_authType);
- mEncType = (Spinner) findViewById(R.id.spinner_encType);
-
- mEasysetupProcess.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
- @Override
- public void onCheckedChanged(RadioGroup group, int checkedId) {
- mGetConfigurationInfo.setVisibility(View.GONE);
- mConfigureSecInfo.setVisibility(View.GONE);
- mProvisionDevPropInfo.setVisibility(View.GONE);
- mProvisionCloudPropInfo.setVisibility(View.GONE);
-
- switch (checkedId) {
- case R.id.btn_configurSec:
- mConfigureSecInfo.setVisibility(View.VISIBLE);
- break;
-
- case R.id.btn_getConfiguration:
- mGetConfigurationInfo.setVisibility(View.VISIBLE);
- break;
-
- case R.id.btn_provisionDevConf:
- mProvisionDevPropInfo.setVisibility(View.VISIBLE);
- break;
-
- case R.id.btn_provisionCloudConf:
- Log.d(TAG, "Starting login activity");
- Intent intent = new Intent(EasysetupActivity.this, LoginActivity.class);
- startActivityForResult(intent, 2);
- mProvisionCloudPropInfo.setVisibility(View.VISIBLE);
- break;
- }
- }
- });
-
- ArrayAdapter<CharSequence> adAuthType, adEnctype;
-
- adAuthType = ArrayAdapter.createFromResource(this, R.array.auth_type,
- android.R.layout.simple_spinner_item);
- adAuthType.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
-
- adEnctype = ArrayAdapter.createFromResource(this, R.array.enc_type,
- android.R.layout.simple_spinner_item);
- adEnctype.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
-
- mAuthType.setAdapter(adAuthType);
- mAuthType.setSelection(0);
-
- mEncType.setAdapter(adEnctype);
- mEncType.setSelection(0);
-
- addListenerForDiscoverEnrollee();
- addListenerForStartConfigureSec();
- addListenerForStartGetConfiguration();
- addListenerForStartProvisionDevProp();
- addListenerForStartProvisionCloudProp();
-
- mSecurityMode.setClickable(false);
- mConfigureSecProcess.setEnabled(false);
- mGetConfigurationProcess.setEnabled(false);
- mProvisionDevPropProcess.setEnabled(false);
- mProvisionCloudPropProcess.setEnabled(false);
-
- mEasySetup = EasySetup.getInstance(getApplicationContext());
-
- initOICStack();
-
- try {
- m_accountManager = OcPlatform.constructAccountManagerObject(
- CIServer,
- EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP));
-
- Log.e(TAG, "constructAccountManagerObject is successful");
- } catch (OcException e) {
- Log.e(TAG, e.toString());
- Log.e(TAG,"Failed to constructAccountManagerObject");
- }
- SharedPreferences settings =
- getApplicationContext().getSharedPreferences("IoTivityCloud", 0);
- mAccessToken = settings.getString("accesstoken", null);
- mRefreshtoken = settings.getString("refreshtoken", null);
- mUserID = settings.getString("uid", null);
-
- if(mRefreshtoken == null)
- {
- Log.d(TAG, "Can not find refresh token");
- }
-
- if(mAccessToken == null && mRefreshtoken == null)
- {
- Log.d(TAG, "Starting login activity");
- Intent intent = new Intent(EasysetupActivity.this, LoginActivity.class);
- startActivityForResult(intent, 1);
- }
- else if(mAccessToken != null)
- {
- SignInDevice();
- }
- }
-
- private void initOICStack() {
- filePath = getFilesDir().getPath() + "/";
-
- SharedPreferences wmbPreference = PreferenceManager.getDefaultSharedPreferences
- (getApplicationContext());
- boolean isFirstRun = wmbPreference.getBoolean("FIRSTRUN", true);
- if (isFirstRun) {
- if(!copyJsonFromAsset())
- {
- Log.e(TAG, "initOICStack error: " + "copyJsonFromAsset()");
- Toast.makeText(this,"Can't Copy DB file from asset, please retry start SampleApp.",
- Toast.LENGTH_LONG).show();
- return;
- }
- SharedPreferences.Editor editor = wmbPreference.edit();
- editor.putBoolean("FIRSTRUN", false);
- editor.commit();
- }
-
- cfg = new PlatformConfig(
- this,
- ServiceType.IN_PROC,
- ModeType.CLIENT_SERVER,
- "0.0.0.0", // bind to all available interfaces
- 0,
- QualityOfService.HIGH, filePath + OIC_CLIENT_JSON_DB_FILE);
- try {
- /*
- * Initialize DataBase
- */
-
- OcPlatform.Configure(cfg);
-
- String sqlDbPath = getFilesDir().getAbsolutePath().replace("files", "databases") +
- File.separator;
- File file = new File(sqlDbPath);
- //check files directory exists
- if (!(file.isDirectory())) {
- file.mkdirs();
- Log.d(TAG, "Sql db directory created at " + sqlDbPath);
- }
- Log.d(TAG, "Sql db directory exists at " + sqlDbPath);
-
- //SQLiteDatabase.openOrCreateDatabase(sqlDbPath+ OIC_SQL_DB_FILE, null);
- OcProvisioning.provisionInit(sqlDbPath + OIC_SQL_DB_FILE);
- mSecurityMode.setChecked(true);
- } catch (OcException e) {
- logMessage(TAG + "provisionInit error: " + e.getMessage());
- Log.e(TAG, e.getMessage());
- Toast.makeText(this,"provisionInit error: " + e.getMessage(),
- Toast.LENGTH_LONG).show();
- mSecurityMode.setChecked(false);
- return;
- } catch (UnsatisfiedLinkError e) {
-
- // Note : Easy setup is built with SECURED = 0, but user still selects Security feature
- // while running the Mediator App it couldn't find "libocprovision.so".
- // As per the programmer guide, security feature should be invoked only if build is done with SECURED = 1.
- mSecurityMode.setChecked(false);
- Log.e(TAG, " Easy setup is built with secured = 0, but executed with security feature");
- Toast.makeText(this,"Security is not enabled [Easy setup is built with SECURED = 0]",
- Toast.LENGTH_LONG).show();
- return;
- }
- }
-
- OcPlatform.OnResourceFoundListener listener =
- new OcPlatform.OnResourceFoundListener() {
- @Override
- public void onFindResourceFailed(Throwable throwable, String s) {
- Log.e(TAG, "Failed found resource, ecode: " + s);
- }
- @Override
- public void onResourceFound(OcResource ocResource) {
- synchronized (mActivity) {
- if(isFirstTime){
- if (null == ocResource) {
- Log.e(TAG, "Found resource is invalid");
- return;
- }
-
- if(ocResource.getHost().contains("+tcp")) {
- Log.d(TAG, "Recv Found resource event from tcp port," +
- "ignoring URI : " + ocResource.getUri());
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- mDiscoverResource.setEnabled(true);
- }
- });
- return;
- }
-
- // Get the resource URI
- String resourceUri = ocResource.getUri();
- // Get the resource host address
- String hostAddress = ocResource.getHost();
- Log.d(TAG,"URI of the resource: " + resourceUri);
- Log.d(TAG,"Host address of the resource: " + hostAddress);
-
- mRemoteEnrollee = mEasySetup.createRemoteEnrollee(ocResource);
-
- if(mRemoteEnrollee == null) {
- Log.d(TAG, "Recv Found resource event," +
- "ignoring URI : " + ocResource.getUri());
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- mDiscoverResource.setEnabled(true);
- }
- });
- return;
- }
-
- isFirstTime = false;
- mEnrolleeDeviceID = ocResource.getServerId();
-
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- mDiscoverResource.setText("Found");
- if(mSecurityMode.isChecked()) {
- mConfigureSecProcess.setEnabled(true);
- }
- mGetConfigurationProcess.setEnabled(true);
- mProvisionDevPropProcess.setEnabled(true);
- mProvisionCloudPropProcess.setEnabled(true);
- }
- });
- }
- }
- }
- };
-
- private void addListenerForDiscoverEnrollee() {
- mDiscoverResource.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- Thread thread = new Thread() {
- boolean result = true;
- @Override
- public void run() {
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- mDiscoverResource.setEnabled(false);
- }
- });
-
- try {
- String requestUri = OcPlatform.WELL_KNOWN_QUERY + "?rt=" + ESConstants.OC_RSRVD_ES_RES_TYPE_EASYSETUP;
- OcPlatform.findResource("",
- requestUri,
- EnumSet.of(OcConnectivityType.CT_DEFAULT),
- listener
- );
- }
- catch (OcException e) {
- e.printStackTrace();
- result = false;
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- mDiscoverResource.setEnabled(true);
- }
- });
- }
- }
- };
-
- thread.start();
- }
- });
- }
-
- private void addListenerForStartConfigureSec() {
- mStartConfigureSec.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- Thread thread = new Thread() {
- @Override
- public void run() {
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- mStartConfigureSec.setEnabled(false);
- }
- });
-
- try {
- mRemoteEnrollee.provisionSecurity(new SecurityProvisioningCallback() {
- @Override
- public void onProgress(final SecurityProvisioningStatus securityProvisioningStatus) {
- if(securityProvisioningStatus.getESResult() == ESResult.ES_OK) {
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- mSecStateText.setText("Success");
- mSecDevIDText.setText(securityProvisioningStatus.getDevUUID());
- }
- });
- }
- else if(securityProvisioningStatus.getESResult()
- == ESResult.ES_SECURE_RESOURCE_DISCOVERY_FAILURE) {
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- mSecStateText.setText("Not found Secure Resource");
- mStartConfigureSec.setEnabled(true);
- }
- });
- }
- else if(securityProvisioningStatus.getESResult()
- == ESResult.ES_OWNERSHIP_TRANSFER_FAILURE) {
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- mSecStateText.setText("Ownership transfer failed");
- mStartConfigureSec.setEnabled(true);
- }
- });
- }
- else {
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- mSecStateText.setText("Failed");
- mStartConfigureSec.setEnabled(true);
- }
- });
- }
- }
- });
- } catch (ESException e) {
- e.printStackTrace();
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- mStartConfigureSec.setEnabled(true);
- }
- });
- }
- }
- };
-
- thread.start();
- }
- });
- }
-
- private void addListenerForStartGetConfiguration(){
- mStartGetConfiguration.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- Thread thread = new Thread() {
- @Override
- public void run() {
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- mGetconfigurationStateText.setText("Process");
- mStartGetConfiguration.setEnabled(false);
- }
- });
-
- try {
- mRemoteEnrollee.getConfiguration(new GetConfigurationCallback() {
- @Override
- public void onProgress(GetConfigurationStatus getConfigurationStatus) {
- if(getConfigurationStatus.getESResult() == ESResult.ES_OK) {
- final EnrolleeConf enrolleeConf = getConfigurationStatus.getEnrolleeConf();
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- mGetconfigurationStateText.setText("Success");
- mDevNameText.setText(enrolleeConf.getDeviceName());
- mModelNumberText.setText(enrolleeConf.getModelNumber());
- setWifiModes(enrolleeConf.getWiFiModes());
- setWifiFreq(enrolleeConf.getWiFiFreq());
-
- if(enrolleeConf.isCloudAccessible()) {
- mCloudAccessableText.setText("TRUE");
- }
- else {
- mCloudAccessableText.setText("FALSE");
- }
- }
- });
- }
- else if(getConfigurationStatus.getESResult() == ESResult.ES_COMMUNICATION_ERROR)
- {
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- mGetconfigurationStateText.setText("Communication Error");
- mStartGetConfiguration.setEnabled(true);
- }
- });
- }
- else {
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- mGetconfigurationStateText.setText("Failed");
- mStartGetConfiguration.setEnabled(true);
- }
- });
- }
- }
- });
- } catch (ESException e) {
- e.printStackTrace();
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- mGetconfigurationStateText.setText("Failed");
- mStartGetConfiguration.setEnabled(true);
- }
- });
- }
- }
- };
-
- thread.start();
- }
- });
- }
-
- private void addListenerForStartProvisionDevProp() {
- mStartProvisionDevProp.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- Thread thread = new Thread() {
- @Override
- public void run() {
- try {
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- mProvisionDevPropState.setText("Progress");
- mStartProvisionDevProp.setEnabled(false);
- }
- });
-
- String enrollerSSID = mEnrollerSsidText.getText().toString();
- String enrollerPW = mEnrollerPWText.getText().toString();
- WIFI_AUTHTYPE authType =
- WIFI_AUTHTYPE.fromInt(mAuthType.getSelectedItemPosition());
- WIFI_ENCTYPE encType =
- WIFI_ENCTYPE.fromInt(mEncType.getSelectedItemPosition());
- String inputLanguage = mInputLanguageText.getText().toString();
- String inputCountry = mInputCountryText.getText().toString();
- String inputLocation = mInputLocationText.getText().toString();
-
- DeviceProp deviceProp = new DeviceProp();
- deviceProp.setWiFiProp(enrollerSSID, enrollerPW, authType, encType);
- deviceProp.setDevConfProp(inputLanguage, inputCountry, inputLocation);
-
- mRemoteEnrollee.provisionDeviceProperties(deviceProp, new DevicePropProvisioningCallback() {
- @Override
- public void onProgress(DevicePropProvisioningStatus devPropProvisioningStatus) {
- final ESResult result = devPropProvisioningStatus.getESResult();
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- if(result.equals(ESResult.ES_OK)) {
- mProvisionDevPropState.setText("Success");
- }
- else if(result.equals(ESResult.ES_ERROR)) {
- mProvisionDevPropState.setText("Failed");
- }
- else if(result.equals(ESResult.ES_COMMUNICATION_ERROR)) {
- mProvisionDevPropState.setText("Communication Error");
- }
- mStartProvisionDevProp.setEnabled(true);
- }
- });
- }
- });
- } catch (ESException e) {
- e.printStackTrace();
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- mProvisionDevPropState.setText("Failed");
- mStartProvisionDevProp.setEnabled(true);
- }
- });
- }
- }
- };
-
- thread.start();
- }
- });
- }
-
- private void addListenerForStartProvisionCloudProp() {
- mStartProvisionCloudProp.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- Thread thread = new Thread() {
- @Override
- public void run() {
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- mProvisionCloudPropState.setText("Progress");
- mStartProvisionCloudProp.setEnabled(false);
- }
- });
-
- try {
- String authCode = mAuthCodeText.getText().toString();
- String authProvider = mAuthProviderText.getText().toString();
- String ciserver = mCIServerText.getText().toString();
-
- CloudProp cloudProp = new CloudProp();
- cloudProp.setCloudProp(authCode, authProvider, ciserver);
- cloudProp.setCloudID("f002ae8b-c42c-40d3-8b8d-1927c17bd1b3");
- cloudProp.setCredID(1);
-
- mRemoteEnrollee.provisionCloudProperties(cloudProp, new CloudPropProvisioningCallback() {
- @Override
- public void onProgress(CloudPropProvisioningStatus cloudProvisioningStatus) {
- final ESResult result = cloudProvisioningStatus.getESResult();
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- if(result.equals(ESResult.ES_ENROLLEE_DISCOVERY_FAILURE)) {
- mProvisionCloudPropState.setText("Not Found Resource");
- }
- else if(result.equals(ESResult.ES_OK)) {
- mProvisionCloudPropState.setText("Cloud Provisioning succeeds");
- }
- else if(result.equals(ESResult.ES_ACL_PROVISIONING_FAILURE)){
- mProvisionCloudPropState.setText("ACL-provisioning fails");
- }
- else if(result.equals(ESResult.ES_CERT_PROVISIONING_FAILURE)){
- mProvisionCloudPropState.setText("CERT-provisioning fails");
- }
- else if(result.equals(ESResult.ES_COMMUNICATION_ERROR)){
- mProvisionCloudPropState.setText("Communication Error");
- }
- else {
- mProvisionCloudPropState.setText("Cloud Provisioning fails");
- }
- }
- });
- }
- });
- } catch (ESException e) {
- e.printStackTrace();
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- mProvisionCloudPropState.setText("Failed");
- mStartProvisionCloudProp.setEnabled(true);
- }
- });
- }
- }
- };
-
- thread.start();
- }
- });
- }
-
- private boolean copyJsonFromAsset() {
- InputStream inputStream = null;
- OutputStream outputStream = null;
- int length;
- byte[] buffer = new byte[BUFFER_SIZE];
- try {
- inputStream = getAssets().open(OIC_CLIENT_JSON_DB_FILE);
- File file = new File(filePath);
- //check files directory exists
- if (!(file.exists() && file.isDirectory())) {
- file.mkdirs();
- }
- outputStream = new FileOutputStream(filePath + OIC_CLIENT_JSON_DB_FILE);
- while ((length = inputStream.read(buffer)) != -1) {
- outputStream.write(buffer, 0, length);
- }
- } catch (NullPointerException e) {
- logMessage(TAG + "Null pointer exception " + e.getMessage());
- Log.e(TAG, e.getMessage());
- return false;
- } catch (FileNotFoundException e) {
- logMessage(TAG + "Json svr db file not found " + e.getMessage());
- Log.e(TAG, e.getMessage());
- return false;
- } catch (IOException e) {
- logMessage(TAG + OIC_CLIENT_JSON_DB_FILE + " file copy failed");
- Log.e(TAG, e.getMessage());
- return false;
- } finally {
- if (inputStream != null) {
- try {
- inputStream.close();
- } catch (IOException e) {
- Log.e(TAG, e.getMessage());
- return false;
- }
- }
- if (outputStream != null) {
- try {
- outputStream.close();
- } catch (IOException e) {
- Log.e(TAG, e.getMessage());
- return false;
- }
- }
- }
- return true;
- }
-
- public void logMessage(String text) {
-
- }
-
- public void setWifiModes(ArrayList<WIFI_MODE> types) {
- String temp = "WIFI - ";
-
- for(WIFI_MODE type : types) {
- if(type.equals(WIFI_MODE.WIFI_11A)) {
- temp = temp + "11A ";
- }
- else if(type.equals(WIFI_MODE.WIFI_11B)) {
- temp = temp + "11B ";
- }
- else if(type.equals(WIFI_MODE.WIFI_11G)) {
- temp = temp + "11G ";
- }
- else if(type.equals(WIFI_MODE.WIFI_11N)) {
- temp = temp + "11N ";
- }
- else if(type.equals(WIFI_MODE.WIFI_11AC)) {
- temp = temp + "11AC ";
- }
- }
- final String modeTypes = temp;
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- mWifiModeText.setText(modeTypes);
- }
- });
- }
-
- public void setWifiFreq(final WIFI_FREQ freq) {
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- if(freq.equals(WIFI_FREQ.WIFI_24G)) {
- mWifiFreqText.setText("2.4G");
- }
- else if(freq.equals(WIFI_FREQ.WIFI_5G)) {
- mWifiFreqText.setText("5G");
- }
- else if(freq.equals(WIFI_FREQ.WIFI_BOTH)) {
- mWifiFreqText.setText("2.4G & 5G");
- }
- }
- });
- }
-
- @Override
- public void onPresence(OcPresenceStatus status, int sequence, String host) {
- final String strStaus = status.getValue();
- Log.d(TAG, "Presence response: " + strStaus + " sequence: " + sequence + " host: " + host);
- runOnUiThread(new Runnable()
- {
- public void run() {
- Toast.makeText(EasysetupActivity.this, "Easy-Setup completed", Toast.LENGTH_SHORT).show();
- }
- });
- }
-
- @Override
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- super.onActivityResult(requestCode, resultCode, data);
- if(resultCode==RESULT_OK && requestCode==1){
- mAuthCode = data.getStringExtra("authCode");
- mAuthProvider = data.getStringExtra("authProvider");
- String text = "Received authCode= " + mAuthCode;
- Log.d(TAG, text);
- SignUpDevice();
- }
- else if(resultCode==RESULT_OK && requestCode==2)
- {
- mEnrolleeAuthCode = data.getStringExtra("authCode");
- mAuthProvider = data.getStringExtra("authProvider");
- mAuthCodeText.setText(mEnrolleeAuthCode);
- mAuthProviderText.setText(mAuthProvider);
- mAuthCodeText.setEnabled(false);
- mAuthProviderText.setEnabled(false);
-
- subscribeDevicePresence();
- }
- }
-
- OcResource.OnPostListener onRefreshTokenPost = new OcResource.OnPostListener() {
- @Override
- public void onPostCompleted(List<OcHeaderOption> list, OcRepresentation ocRepresentation) {
- Log.d(TAG, "onRefreshTokenPost..");
- try {
- mAccessToken = ocRepresentation.getValue("accesstoken");
- mRefreshtoken = ocRepresentation.getValue("refreshtoken");
-
- saveCloudTokenAtSharedPreferences();
- }
- catch (OcException e)
- {
- e.printStackTrace();
- }
-
- SignInDevice();
- }
-
- @Override
- public void onPostFailed(Throwable throwable) {
- Log.d(TAG, "onRefreshTokenPost failed..");
- }
- };
-
- public void RefreshToken() {
- try {
- OcResource authResource = OcPlatform.constructResourceObject(CIServer, "/.well-known/ocf/account/tokenrefresh",
- EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP, OcConnectivityType.CT_IP_USE_V4),
- false, Arrays.asList("oic.wk.account"), Arrays.asList(OcPlatform.DEFAULT_INTERFACE));
- OcRepresentation rep = new OcRepresentation();
-
- runOnUiThread(new Runnable()
- {
- public void run() {
- Toast.makeText(EasysetupActivity.this, "RefreshToken in progress..", Toast.LENGTH_SHORT).show();
- }
- });
-
- rep.setValue("di", deviceID);
- rep.setValue("granttype", "refresh_token");
- rep.setValue("refreshtoken", mRefreshtoken);
- rep.setValue("uid", mUserID);
- authResource.post(rep, new HashMap<String, String>(), onRefreshTokenPost);
- }
- catch(OcException e)
- {
- e.printStackTrace();
- }
-
- Log.d(TAG, "No error while executing login");
- }
-
- private void saveCloudTokenAtSharedPreferences() {
- Log.d(TAG, "accesstoken: " + mAccessToken);
- SharedPreferences settings = getApplicationContext().getSharedPreferences("IoTivityCloud", 0);
- SharedPreferences.Editor editor = settings.edit();
- editor.putString("accesstoken", mAccessToken);
- editor.putString("refreshtoken", mRefreshtoken);
- editor.putString("uid", mUserID);
-
- if(editor.commit() == true)
- Log.d(TAG, "accesstoken saved");
- else
- Log.d(TAG, "accesstoken not saved");
- }
-
- OcAccountManager.OnPostListener onSignUpPost = new OcAccountManager.OnPostListener() {
- @Override
- public void onPostCompleted(List<OcHeaderOption> list, OcRepresentation ocRepresentation) {
- Log.d(TAG, "onSignUpPost..");
- try {
- runOnUiThread(new Runnable()
- {
- public void run() {
- Toast.makeText(EasysetupActivity.this, "Sign-up completed", Toast.LENGTH_SHORT).show();
- }
- });
-
- mAccessToken = ocRepresentation.getValue("accesstoken");
- mRefreshtoken = ocRepresentation.getValue("refreshtoken");
- mUserID = ocRepresentation.getValue("uid");
-
- if(mAccessToken != null)
- {
- saveCloudTokenAtSharedPreferences();
- SignInDevice();
- }
- //TODO : save certificate
- }
- catch (OcException e)
- {
- e.printStackTrace();
- }
- }
-
- @Override
- public void onPostFailed(Throwable throwable) {
- Log.d(TAG, "onSignUpPost failed.. : " + throwable.getMessage());
- }
- };
-
- private void SignUpDevice() {
- try {
- Log.d(TAG, "SignUpDevice..");
-
- runOnUiThread(new Runnable()
- {
- public void run() {
- Toast.makeText(EasysetupActivity.this, "SignUpDevice in progress..", Toast.LENGTH_SHORT).show();
- }
- });
-
- if(m_accountManager != null) {
- m_accountManager.signUp(mAuthProvider, mAuthCode, onSignUpPost);
- }
- }
- catch(OcException e)
- {
- e.printStackTrace();
- }
-
- Log.d(TAG, "No error while executing SignUp");
- }
-
- OcAccountManager.OnPostListener onSignInPost = new OcAccountManager.OnPostListener() {
- @Override
- public void onPostCompleted(List<OcHeaderOption> list, OcRepresentation ocRepresentation) {
- Log.d(TAG, "onSignInPost..");
-
- runOnUiThread(new Runnable()
- {
- public void run() {
- Toast.makeText(EasysetupActivity.this, "Sign-in completed", Toast.LENGTH_SHORT).show();
- }
- });
- }
-
- @Override
- public void onPostFailed(Throwable ex) {
- if (ex instanceof OcException) {
- OcException ocEx = (OcException) ex;
- ErrorCode errCode = ocEx.getErrorCode();
- Log.e(TAG, ocEx.getMessage());
- if (ErrorCode.UNAUTHORIZED_REQ != errCode) {
- RefreshToken();
- }
- }
- }
- };
-
- private void SignInDevice() {
- try {
- Log.d(TAG, "SignInDevice..");
-
- runOnUiThread(new Runnable()
- {
- public void run() {
- Toast.makeText(EasysetupActivity.this, "SignInDevice in progress..", Toast.LENGTH_SHORT).show();
- }
- });
- if(m_accountManager != null) {
- m_accountManager.signIn(mUserID, mAccessToken, onSignInPost);
- }
- }
- catch(OcException e)
- {
- e.printStackTrace();
- }
-
- Log.d(TAG, "No error while executing login");
- }
-
- @Override
- public void onObserveCompleted(List<OcHeaderOption> list, OcRepresentation ocRepresentation, int i) {
- Log.d(TAG,"onObserveCompleted");
- }
-
- @Override
- public void onObserveFailed(Throwable throwable) {
- Log.d(TAG,"onObserveFailed");
- }
-
- public void subscribeDevicePresence()
- {
- List<String> deviceIDs = new ArrayList<String>();
- deviceIDs.add(mEnrolleeDeviceID);
-
- try {
-
- OcPlatform.subscribeDevicePresence(CIServer, deviceIDs, EnumSet.of(OcConnectivityType.
- CT_ADAPTER_TCP), this);
- } catch(OcException e)
- {
- e.printStackTrace();
- }
-
- }
-
- @Override
- protected void onDestroy() {
- super.onDestroy();
- }
-}
+++ /dev/null
-/**
- * ***************************************************************
- * <p/>
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- * <p/>
- * <p/>
- * <p/>
- * 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
- * <p/>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p/>
- * 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.
- * <p/>
- * ****************************************************************
- */
-
-package org.iotivity.service.easysetup;
-
-import android.app.Activity;
-import android.app.AlertDialog;
-import android.content.DialogInterface;
-import android.content.Intent;
-import android.content.SharedPreferences;
-import android.net.ConnectivityManager;
-import android.net.NetworkInfo;
-import android.net.UrlQuerySanitizer;
-import android.net.wifi.WifiConfiguration;
-import android.net.wifi.WifiManager;
-import android.os.Bundle;
-import android.os.Handler;
-import android.os.Message;
-import android.preference.PreferenceManager;
-import android.util.Log;
-import android.view.View;
-import android.view.View.OnClickListener;
-import android.webkit.WebView;
-import android.webkit.WebViewClient;
-import android.widget.Button;
-import android.widget.EditText;
-import android.widget.LinearLayout;
-import android.widget.ProgressBar;
-import android.widget.RadioButton;
-import android.widget.RelativeLayout;
-import android.widget.TextView;
-import android.widget.Toast;
-
-import org.iotivity.base.ModeType;
-import org.iotivity.base.OcException;
-import org.iotivity.base.OcPlatform;
-import org.iotivity.base.OcProvisioning;
-import org.iotivity.base.PlatformConfig;
-import org.iotivity.base.QualityOfService;
-import org.iotivity.base.ServiceType;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-
-
-public class LoginActivity extends Activity {
- private static final String TAG = "Easysetup Login: ";
-
- /* Samsung account */
- private WebView mWebView = null;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_login);
-
- /* For Samsung account authentifaction */
- mWebView = (WebView) findViewById(R.id.webView);
- mWebView.setVisibility(View.VISIBLE);
- mWebView.setInitialScale(200);
- mWebView.getSettings().setJavaScriptEnabled(true);
- //mWebView.getSettings().setSupportZoom(true);
- mWebView.getSettings().setBuiltInZoomControls(true);
- mWebView.setWebViewClient(new WebViewClientClass());
-
- mWebView.loadUrl("https://github.com/login?return_to=%2Flogin%2Foauth%2Fauthorize%3Fclient_id%3Dea9c18f540323b0213d0%26redirect_uri%3Dhttp%253A%252F%252Fwww.example.com%252Foauth_callback%252F");
- }
-
- public void onDestroy() {
- super.onDestroy();
- }
-
- private class WebViewClientClass extends WebViewClient {
-
- @Override
- public void onPageFinished(WebView view, String url) {
- Log.e(TAG, "called!!! url=" + url);
-
- if(url.contains("http://www.example.com/oauth_callback/")){
-
- mWebView.setVisibility(View.INVISIBLE);
-
- //parsing url
- UrlQuerySanitizer sanitizer = new UrlQuerySanitizer();
- sanitizer.setAllowUnregisteredParamaters(true);
- sanitizer.parseUrl(url);
-
- String mAuthCode = null;
- mAuthCode = sanitizer.getValue("code");
-
- Intent intent = getIntent();
- intent.putExtra("authCode", mAuthCode);
- intent.putExtra("authProvider", "github");
-
- setResult(RESULT_OK, intent);
-
- finish();
- }
- }
- }
-}
+++ /dev/null
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical"
- android:id="@+id/loginlayout"
- tools:context="org.iotivity.service.easysetup.mediator.LoginActivity">
-
- <WebView
- android:id="@+id/webView"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:visibility="visible" />
-
-</LinearLayout>
+++ /dev/null
-<?xml version="1.0" encoding="utf-8"?>\r
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"\r
- android:orientation="vertical" android:layout_width="match_parent"\r
- android:layout_height="match_parent"\r
- android:baselineAligned="true"\r
- android:weightSum="1"\r
- android:nestedScrollingEnabled="false">\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content">\r
-\r
- <Button\r
- android:layout_width="wrap_content"\r
- android:layout_height="wrap_content"\r
- android:text="Discovery"\r
- android:id="@+id/btn_discoverResource"\r
- android:layout_marginLeft="20dp"\r
- android:layout_marginTop="10dp" />\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="match_parent"\r
- android:weightSum="1"\r
- android:baselineAligned="true"\r
- android:layout_marginLeft="20dp"\r
- android:id="@+id/layout_Security"\r
- android:layout_marginRight="20dp">\r
-\r
- <TextView\r
- android:layout_width="wrap_content"\r
- android:layout_height="wrap_content"\r
- android:text="@string/security_mode"\r
- android:id="@+id/text_EnableSecurity"\r
- android:phoneNumber="false"\r
- android:textSize="16sp"\r
- android:layout_marginTop="10dp"\r
- android:layout_marginLeft="20dp" />\r
-\r
- <ToggleButton\r
- android:layout_width="wrap_content"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/btn_Security"\r
- android:layout_marginLeft="40dp"\r
- android:layout_weight="0"\r
- android:textOff="Disable"\r
- android:textOn="Enable"\r
- android:layout_marginTop="10dp" />\r
-\r
- </LinearLayout>\r
-\r
- </LinearLayout>\r
-\r
- <View\r
- android:layout_height="2dip"\r
- android:background="#FF909090"\r
- android:layout_marginTop="10dp"\r
- android:layout_marginBottom="10dp"\r
- android:layout_marginLeft="15dp"\r
- android:layout_marginRight="15dp"\r
- android:layout_width="match_parent" />\r
-\r
- <LinearLayout\r
- android:orientation="vertical"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/layout_Excution"\r
- android:layout_marginLeft="10dp"\r
- android:layout_marginRight="10dp">\r
-\r
- <TextView\r
- android:layout_width="wrap_content"\r
- android:layout_height="wrap_content"\r
- android:text="@string/easysetup_sequence"\r
- android:id="@+id/textView22"\r
- android:layout_marginLeft="10dp"\r
- android:textSize="16sp" />\r
-\r
- <RadioGroup\r
- android:layout_width="match_parent"\r
- android:layout_height="match_parent"\r
- android:layout_marginTop="5dp"\r
- android:id="@+id/rg_EasysetupProcess"\r
- android:layout_marginLeft="20dp">\r
-\r
- <RadioButton\r
- android:layout_width="160dp"\r
- android:layout_height="32dp"\r
- android:text="@string/securityprovisioning"\r
- android:id="@+id/btn_configurSec"\r
- android:checked="false"\r
- android:textSize="12sp" />\r
-\r
- <RadioButton\r
- android:layout_width="160dp"\r
- android:layout_height="32dp"\r
- android:text="GetConfiguration"\r
- android:id="@+id/btn_getConfiguration"\r
- android:checked="false"\r
- android:textSize="12sp" />\r
-\r
- <RadioButton\r
- android:layout_width="173dp"\r
- android:layout_height="32dp"\r
- android:text="ProvisionDeviceConfig"\r
- android:id="@+id/btn_provisionDevConf"\r
- android:textSize="12sp" />\r
-\r
- <RadioButton\r
- android:layout_width="160dp"\r
- android:layout_height="32dp"\r
- android:text="@string/cloudprovisioning"\r
- android:id="@+id/btn_provisionCloudConf"\r
- android:textSize="12sp" />\r
- </RadioGroup>\r
-\r
- </LinearLayout>\r
-\r
- <View\r
- android:layout_height="2dip"\r
- android:background="#FF909090"\r
- android:layout_marginTop="10dp"\r
- android:layout_marginBottom="10dp"\r
- android:layout_marginLeft="15dp"\r
- android:layout_marginRight="15dp"\r
- android:layout_width="match_parent" />\r
-\r
- <ScrollView\r
- android:layout_width="fill_parent"\r
- android:layout_height="fill_parent"\r
- android:id="@+id/scrollView" >\r
-\r
- <LinearLayout\r
- android:orientation="vertical"\r
- android:layout_width="match_parent"\r
- android:layout_height="match_parent"\r
- android:id="@+id/layout_Infomation"\r
- android:gravity="center_horizontal"\r
- android:weightSum="1">\r
-\r
- <LinearLayout\r
- android:orientation="vertical"\r
- android:layout_width="match_parent"\r
- android:layout_height="match_parent"\r
- android:layout_marginLeft="20dp"\r
- android:layout_marginRight="20dp"\r
- android:id="@+id/layout_ConfigurSec"\r
- android:layout_marginTop="10dp"\r
- android:weightSum="1"\r
- android:visibility="gone">\r
-\r
- <TextView\r
- android:layout_width="wrap_content"\r
- android:layout_height="wrap_content"\r
- android:textAppearance="?android:attr/textAppearanceSmall"\r
- android:text="@string/security_provisioning_state"\r
- android:id="@+id/textView10" />\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/layout_secState"\r
- android:weightSum="1"\r
- android:layout_marginLeft="10dp"\r
- android:layout_marginTop="10dp" >\r
-\r
- <TextView\r
- android:layout_width="80dp"\r
- android:layout_height="wrap_content"\r
- android:text="State"\r
- android:id="@+id/textView12"\r
- android:layout_gravity="center_vertical" />\r
-\r
- <TextView\r
- android:layout_width="wrap_content"\r
- android:layout_height="wrap_content"\r
- android:text="empty"\r
- android:id="@+id/txt_secState" />\r
-\r
- </LinearLayout>\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/linearLayout2"\r
- android:weightSum="1"\r
- android:layout_marginLeft="10dp"\r
- android:layout_marginTop="10dp" >\r
-\r
- <TextView\r
- android:layout_width="80dp"\r
- android:layout_height="wrap_content"\r
- android:text="Device ID"\r
- android:id="@+id/textView"\r
- android:layout_gravity="center_vertical" />\r
-\r
- <TextView\r
- android:layout_width="wrap_content"\r
- android:layout_height="wrap_content"\r
- android:text="empty"\r
- android:id="@+id/txt_secDevID" />\r
- </LinearLayout>\r
-\r
- <FrameLayout\r
- android:layout_width="match_parent"\r
- android:layout_height="82dp"\r
- android:layout_weight="0.64"></FrameLayout>\r
-\r
- <Button\r
- android:layout_width="90dp"\r
- android:layout_height="wrap_content"\r
- android:text="START"\r
- android:id="@+id/btn_startConfigureSec"\r
- android:layout_marginTop="10dp"\r
- android:layout_gravity="bottom|right" />\r
-\r
- </LinearLayout>\r
-\r
- <LinearLayout\r
- android:orientation="vertical"\r
- android:layout_width="match_parent"\r
- android:layout_height="match_parent"\r
- android:layout_marginLeft="20dp"\r
- android:layout_marginRight="20dp"\r
- android:id="@+id/layout_GetConfiguration"\r
- android:layout_marginTop="10dp"\r
- android:visibility="gone">\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content">\r
-\r
- <TextView\r
- android:layout_width="wrap_content"\r
- android:layout_height="wrap_content"\r
- android:textAppearance="?android:attr/textAppearanceSmall"\r
- android:text="@string/enrollee_property_data"\r
- android:id="@+id/textView4" />\r
-\r
- <TextView\r
- android:layout_width="wrap_content"\r
- android:layout_height="wrap_content"\r
- android:text="state : "\r
- android:id="@+id/textView18"\r
- android:layout_marginLeft="80dp" />\r
-\r
- <TextView\r
- android:layout_width="wrap_content"\r
- android:layout_height="wrap_content"\r
- android:text="wait"\r
- android:id="@+id/txt_getConfigurationState" />\r
- </LinearLayout>\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/layout_devID"\r
- android:weightSum="1"\r
- android:layout_marginLeft="10dp"\r
- android:layout_marginTop="10dp" >\r
-\r
- <TextView\r
- android:layout_width="130dp"\r
- android:layout_height="wrap_content"\r
- android:text="devID"\r
- android:id="@+id/textView6"\r
- android:layout_gravity="center_vertical" />\r
-\r
- <TextView\r
- android:layout_width="wrap_content"\r
- android:layout_height="wrap_content"\r
- android:text="empty"\r
- android:id="@+id/txt_devID" />\r
-\r
- </LinearLayout>\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/layout_devName"\r
- android:weightSum="1"\r
- android:layout_marginLeft="10dp"\r
- android:layout_marginTop="10dp" >\r
-\r
- <TextView\r
- android:layout_width="130dp"\r
- android:layout_height="wrap_content"\r
- android:text="devName"\r
- android:id="@+id/textView7"\r
- android:layout_gravity="center_vertical" />\r
-\r
- <TextView\r
- android:layout_width="wrap_content"\r
- android:layout_height="wrap_content"\r
- android:text="empty"\r
- android:id="@+id/txt_devName" />\r
-\r
- </LinearLayout>\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/layout_modelNumber"\r
- android:weightSum="1"\r
- android:layout_marginLeft="10dp"\r
- android:layout_marginTop="10dp" >\r
-\r
- <TextView\r
- android:layout_width="130dp"\r
- android:layout_height="wrap_content"\r
- android:text="modelNumber"\r
- android:id="@+id/textView7"\r
- android:layout_gravity="center_vertical" />\r
-\r
- <TextView\r
- android:layout_width="wrap_content"\r
- android:layout_height="wrap_content"\r
- android:text="empty"\r
- android:id="@+id/txt_modelNumber" />\r
-\r
- </LinearLayout>\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/layout_Language"\r
- android:weightSum="1"\r
- android:layout_marginLeft="10dp"\r
- android:layout_marginTop="10dp" >\r
-\r
- <TextView\r
- android:layout_width="130dp"\r
- android:layout_height="wrap_content"\r
- android:text="language"\r
- android:id="@+id/textView8"\r
- android:layout_gravity="center_vertical" />\r
-\r
- <TextView\r
- android:layout_width="wrap_content"\r
- android:layout_height="wrap_content"\r
- android:text="empty"\r
- android:id="@+id/txt_language" />\r
-\r
- </LinearLayout>\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/layout_Country"\r
- android:weightSum="1"\r
- android:layout_marginLeft="10dp"\r
- android:layout_marginTop="10dp" >\r
-\r
- <TextView\r
- android:layout_width="130dp"\r
- android:layout_height="wrap_content"\r
- android:text="country"\r
- android:id="@+id/textView9"\r
- android:layout_gravity="center_vertical" />\r
-\r
- <TextView\r
- android:layout_width="wrap_content"\r
- android:layout_height="wrap_content"\r
- android:text="empty"\r
- android:id="@+id/txt_country" />\r
-\r
- </LinearLayout>\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/layout_wifimode"\r
- android:weightSum="1"\r
- android:layout_marginLeft="10dp"\r
- android:layout_marginTop="10dp" >\r
-\r
- <TextView\r
- android:layout_width="130dp"\r
- android:layout_height="wrap_content"\r
- android:text="wifi mode"\r
- android:id="@+id/textView20"\r
- android:layout_gravity="center_vertical" />\r
-\r
- <TextView\r
- android:layout_width="wrap_content"\r
- android:layout_height="wrap_content"\r
- android:text="empty"\r
- android:id="@+id/txt_wifiMode" />\r
-\r
- </LinearLayout>\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/layout_wififreq"\r
- android:weightSum="1"\r
- android:layout_marginLeft="10dp"\r
- android:layout_marginTop="10dp" >\r
-\r
- <TextView\r
- android:layout_width="130dp"\r
- android:layout_height="wrap_content"\r
- android:text="wifi freq"\r
- android:id="@+id/textView21"\r
- android:layout_gravity="center_vertical" />\r
-\r
- <TextView\r
- android:layout_width="wrap_content"\r
- android:layout_height="wrap_content"\r
- android:text="empty"\r
- android:id="@+id/txt_wifiFreq" />\r
-\r
- </LinearLayout>\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/layout_coludAccessAble"\r
- android:weightSum="1"\r
- android:layout_marginLeft="10dp"\r
- android:layout_marginTop="10dp" >\r
-\r
- <TextView\r
- android:layout_width="130dp"\r
- android:layout_height="wrap_content"\r
- android:text="CloudAccessable"\r
- android:id="@+id/textView14"\r
- android:layout_gravity="center_vertical" />\r
-\r
- <TextView\r
- android:layout_width="wrap_content"\r
- android:layout_height="wrap_content"\r
- android:text="empty"\r
- android:id="@+id/txt_cloudAccessable" />\r
-\r
- </LinearLayout>\r
-\r
- <Button\r
- android:layout_width="90dp"\r
- android:layout_height="wrap_content"\r
- android:text="@string/start"\r
- android:id="@+id/btn_startGetConfiguration"\r
- android:layout_gravity="bottom|right" />\r
-\r
- </LinearLayout>\r
-\r
- <LinearLayout\r
- android:orientation="vertical"\r
- android:layout_width="match_parent"\r
- android:layout_height="match_parent"\r
- android:layout_marginLeft="20dp"\r
- android:layout_marginRight="20dp"\r
- android:id="@+id/layout_ProvisionDevConf"\r
- android:layout_marginTop="10dp"\r
- android:visibility="gone">\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content">\r
-\r
- <TextView\r
- android:layout_width="wrap_content"\r
- android:layout_height="wrap_content"\r
- android:textAppearance="?android:attr/textAppearanceSmall"\r
- android:text="@string/enroller_infomation"\r
- android:id="@+id/textView_DataProvisioning" />\r
-\r
- <TextView\r
- android:layout_width="wrap_content"\r
- android:layout_height="wrap_content"\r
- android:text="state : "\r
- android:id="@+id/textView19"\r
- android:layout_marginLeft="80dp" />\r
-\r
- <TextView\r
- android:layout_width="wrap_content"\r
- android:layout_height="wrap_content"\r
- android:text="wait"\r
- android:id="@+id/txt_provisionDevConfState" />\r
- </LinearLayout>\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/layout_EnrollerSSID"\r
- android:weightSum="1"\r
- android:layout_marginLeft="10dp"\r
- android:layout_marginTop="10dp">\r
-\r
- <TextView\r
- android:layout_width="130dp"\r
- android:layout_height="wrap_content"\r
- android:text="@string/enroller_ssid"\r
- android:id="@+id/txt_ssid"\r
- android:layout_gravity="center_vertical" />\r
-\r
- <EditText\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/editText_EnrollerSSID"\r
- android:text="Test_SSID"\r
- android:layout_marginLeft="20dp"\r
- android:layout_gravity="center_vertical" />\r
- </LinearLayout>\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/layout_EnrollerPW"\r
- android:weightSum="1"\r
- android:layout_marginLeft="10dp"\r
- android:layout_marginTop="10dp" >\r
-\r
- <TextView\r
- android:layout_width="130dp"\r
- android:layout_height="wrap_content"\r
- android:text="Enter Enroller's PW"\r
- android:id="@+id/txt_pass"\r
- android:layout_gravity="center_vertical" />\r
-\r
- <EditText\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/editText_EnrollerPW"\r
- android:text="Test_PW"\r
- android:layout_marginLeft="20dp"\r
- android:layout_gravity="center_vertical" />\r
- </LinearLayout>\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/layout_InputLanguage"\r
- android:weightSum="1"\r
- android:layout_marginLeft="10dp"\r
- android:layout_marginTop="10dp" >\r
-\r
- <TextView\r
- android:layout_width="130dp"\r
- android:layout_height="wrap_content"\r
- android:text="language"\r
- android:id="@+id/textView25"\r
- android:layout_gravity="center_vertical" />\r
-\r
- <EditText\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/editText_Language"\r
- android:text="Test_Language"\r
- android:layout_marginLeft="20dp"\r
- android:layout_gravity="center_vertical" />\r
-\r
- </LinearLayout>\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/layout_InputCountry"\r
- android:weightSum="1"\r
- android:layout_marginLeft="10dp"\r
- android:layout_marginTop="10dp" >\r
-\r
- <TextView\r
- android:layout_width="130dp"\r
- android:layout_height="wrap_content"\r
- android:text="country"\r
- android:id="@+id/textView23"\r
- android:layout_gravity="center_vertical" />\r
-\r
- <EditText\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/editText_Country"\r
- android:text="Test_Country"\r
- android:layout_marginLeft="20dp"\r
- android:layout_gravity="center_vertical" />\r
- </LinearLayout>\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/layout_InputLocation"\r
- android:weightSum="1"\r
- android:layout_marginLeft="10dp"\r
- android:layout_marginTop="10dp" >\r
-\r
- <TextView\r
- android:layout_width="130dp"\r
- android:layout_height="wrap_content"\r
- android:text="location"\r
- android:id="@+id/textView23"\r
- android:layout_gravity="center_vertical" />\r
-\r
- <EditText\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/editText_Location"\r
- android:text="Test_Location"\r
- android:layout_marginLeft="20dp"\r
- android:layout_gravity="center_vertical" />\r
- </LinearLayout>\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/layout_EnrollerAuthType"\r
- android:weightSum="1"\r
- android:layout_marginLeft="10dp"\r
- android:layout_marginTop="10dp" >\r
-\r
- <TextView\r
- android:layout_width="130dp"\r
- android:layout_height="wrap_content"\r
- android:text="@string/select_enroller_authentication_type"\r
- android:id="@+id/txt_authtype"\r
- android:layout_gravity="center_vertical" />\r
-\r
- <Spinner\r
- android:layout_width="fill_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/spinner_authType"\r
- android:layout_marginLeft="20dp"\r
- android:layout_gravity="center_vertical"\r
- android:spinnerMode="dropdown" />\r
-\r
- </LinearLayout>\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/layout_EnrollerEncType"\r
- android:weightSum="1"\r
- android:layout_marginLeft="10dp"\r
- android:layout_marginTop="10dp" >\r
-\r
- <TextView\r
- android:layout_width="130dp"\r
- android:layout_height="wrap_content"\r
- android:text="@string/select_enroller_encription_type"\r
- android:id="@+id/textView5"\r
- android:layout_gravity="center_vertical" />\r
-\r
- <Spinner\r
- android:layout_width="fill_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/spinner_encType"\r
- android:layout_marginLeft="20dp"\r
- android:layout_gravity="center_vertical"\r
- android:spinnerMode="dropdown" />\r
-\r
- </LinearLayout>\r
-\r
- <Button\r
- android:layout_width="90dp"\r
- android:layout_height="wrap_content"\r
- android:text="START"\r
- android:id="@+id/btn_startProvisionDevConf"\r
- android:layout_marginTop="10dp"\r
- android:layout_gravity="bottom|right" />\r
-\r
- </LinearLayout>\r
-\r
- <LinearLayout\r
- android:orientation="vertical"\r
- android:layout_width="match_parent"\r
- android:layout_height="match_parent"\r
- android:layout_marginLeft="20dp"\r
- android:layout_marginRight="20dp"\r
- android:id="@+id/layout_ProvisionCloudConf"\r
- android:layout_marginTop="10dp"\r
- android:visibility="gone">\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content">\r
-\r
- <TextView\r
- android:layout_width="wrap_content"\r
- android:layout_height="wrap_content"\r
- android:textAppearance="?android:attr/textAppearanceSmall"\r
- android:text="Cloud Information"\r
- android:id="@+id/textView15" />\r
-\r
- <TextView\r
- android:layout_width="wrap_content"\r
- android:layout_height="wrap_content"\r
- android:text="state : "\r
- android:id="@+id/textView24"\r
- android:layout_marginLeft="80dp" />\r
-\r
- <TextView\r
- android:layout_width="wrap_content"\r
- android:layout_height="wrap_content"\r
- android:text="wait"\r
- android:id="@+id/txt_provisionCloudConfState" />\r
- </LinearLayout>\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/linearLayout11"\r
- android:weightSum="1"\r
- android:layout_marginLeft="10dp"\r
- android:layout_marginTop="10dp" >\r
-\r
- <TextView\r
- android:layout_width="130dp"\r
- android:layout_height="wrap_content"\r
- android:text="Enter Target Cloud's Authcode"\r
- android:id="@+id/textView16"\r
- android:layout_gravity="center_vertical" />\r
-\r
- <EditText\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/editText_authcode"\r
- android:layout_marginLeft="20dp"\r
- android:layout_gravity="center_vertical"\r
- android:text="authcode" />\r
- </LinearLayout>\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/linearLayout12"\r
- android:weightSum="1"\r
- android:layout_marginLeft="10dp"\r
- android:layout_marginTop="10dp" >\r
-\r
- <TextView\r
- android:layout_width="130dp"\r
- android:layout_height="wrap_content"\r
- android:text="Enter Target Cloud's AuthProvider"\r
- android:id="@+id/textView17"\r
- android:layout_gravity="center_vertical" />\r
-\r
- <EditText\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/editText_authprovider"\r
- android:layout_marginLeft="20dp"\r
- android:layout_gravity="center_vertical"\r
- android:text="authprovider" />\r
- </LinearLayout>\r
-\r
- <LinearLayout\r
- android:orientation="horizontal"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/linearLayout"\r
- android:weightSum="1"\r
- android:layout_marginLeft="10dp"\r
- android:layout_marginTop="10dp" >\r
-\r
- <TextView\r
- android:layout_width="130dp"\r
- android:layout_height="wrap_content"\r
- android:text="Enter Target Cloud's Interface server"\r
- android:id="@+id/textView3"\r
- android:layout_gravity="center_vertical" />\r
-\r
- <EditText\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:id="@+id/editText_ciserver"\r
- android:layout_marginLeft="20dp"\r
- android:layout_gravity="center_vertical"\r
- android:text="coap+tcp://52.69.149.85:5683" />\r
- </LinearLayout>\r
-\r
- <Button\r
- android:layout_width="90dp"\r
- android:layout_height="wrap_content"\r
- android:text="START"\r
- android:id="@+id/btn_startProvisionCloudConf"\r
- android:layout_marginTop="10dp"\r
- android:layout_gravity="bottom|right" />\r
-\r
- </LinearLayout>\r
- </LinearLayout>\r
- </ScrollView>\r
-\r
-</LinearLayout>
\ No newline at end of file
+++ /dev/null
-<menu xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:app="http://schemas.android.com/apk/res-auto"
- xmlns:tools="http://schemas.android.com/tools"
- tools:context="org.iotivity.service.easysetup.MainActivity" >
-
- <item
- android:id="@+id/action_settings"
- android:orderInCategory="100"
- android:title="@string/action_settings"/>
-
-</menu>
+++ /dev/null
-<?xml version="1.0" encoding="utf-8"?>\r
-<resources>\r
- <string-array name="auth_type">\r
- <item>NONE_AUTH</item>\r
- <item>WEP</item>\r
- <item>WPA_PSK</item>\r
- <item>WPA2_PSK</item>\r
- </string-array>\r
- <string-array name="enc_type">\r
- <item>NONE_ENC</item>\r
- <item>WEP_64</item>\r
- <item>WEP_128</item>\r
- <item>TKIP</item>\r
- <item>AES</item>\r
- <item>TKIP_AES</item>\r
- </string-array>\r
-</resources>
\ No newline at end of file
+++ /dev/null
-<resources>
-
- <!-- Default screen margins, per the Android Design guidelines. -->
- <dimen name="activity_horizontal_margin">16dp</dimen>
- <dimen name="activity_vertical_margin">1dp</dimen>
-
-</resources>
+++ /dev/null
-<?xml version="1.0" encoding="utf-8"?>
-<resources>
- <string name="app_name">Easy Setup</string>
- <string name="action_settings">Settings</string>
-
- <string name="security_mode">Security Mode</string>
- <string name="enroller_ssid">Enter Enroller\'s SSID</string>
- <string name="select_enroller_authentication_type">Select Enroller\'s Authentication Type</string>
- <string name="select_enroller_encription_type">Select Enroller\'s Encription Type</string>
- <string name="enroller_infomation">Enroller\'s Infomation</string>
- <string name="requsetpropertydata">RequsetPropertyData</string>
- <string name="securityprovisioning">SecurityProvisioning</string>
- <string name="dataprovisioning">DataProvisioning</string>
- <string name="cloudprovisioning">CloudProvisioning</string>
- <string name="log">log</string>
- <string name="start">START</string>
- <string name="enrollee_property_data">Enrollee\'s Property Data</string>
- <string name="enter_enroller_apos_s_pw">Enter Enroller\'s PW</string>
- <string name="easysetup_sequence">Easysetup Sequence</string>
- <string name="security_provisioning_state">Security Provisioning State</string>
-
-
-</resources>
+++ /dev/null
-<resources>
-
- <!--
- Base application theme, dependent on API level. This theme is replaced
- by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
- -->
- <style name="AppBaseTheme" parent="android:Theme.Light">
- <!--
- Theme customizations available in newer API levels can go in
- res/values-vXX/styles.xml, while customizations related to
- backward-compatibility can go here.
- -->
- </style>
-
- <!-- Application theme. -->
- <style name="AppTheme" parent="AppBaseTheme">
- <!-- All customizations that are NOT specific to a particular API-level can go here. -->
- </style>
-
-</resources>
+++ /dev/null
-//******************************************************************\r
-//\r
-// Copyright 2016 Samsung Electronics All Rights Reserved.\r
-//\r
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
-//\r
-// Licensed under the Apache License, Version 2.0 (the "License");\r
-// you may not use this file except in compliance with the License.\r
-// You may obtain a copy of the License at\r
-//\r
-// http://www.apache.org/licenses/LICENSE-2.0\r
-//\r
-// Unless required by applicable law or agreed to in writing, software\r
-// distributed under the License is distributed on an "AS IS" BASIS,\r
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-// See the License for the specific language governing permissions and\r
-// limitations under the License.\r
-//\r
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
-\r
-// Top-level build file where you can add configuration options common to all sub-projects/modules.\r
-\r
-buildscript {\r
- repositories {\r
- jcenter()\r
- }\r
- dependencies {\r
- classpath 'com.android.tools.build:gradle:1.3.0'\r
-\r
- // NOTE: Do not place your application dependencies here; they belong\r
- // in the individual module build.gradle files\r
- }\r
-}\r
-\r
-allprojects {\r
- repositories {\r
- jcenter()\r
- }\r
-}\r
+++ /dev/null
-#
-# //******************************************************************
-# //
-# // Copyright 2016 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.
-# //
-# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#
-
-# Project-wide Gradle settings.
-
-# IDE (e.g. Android Studio) users:
-# Gradle settings configured through the IDE *will override*
-# any settings specified in this file.
-
-# For more details on how to configure your build environment visit
-# http://www.gradle.org/docs/current/userguide/build_environment.html
-
-# Specifies the JVM arguments used for the daemon process.
-# The setting is particularly useful for tweaking memory settings.
-# Default value: -Xmx10248m -XX:MaxPermSize=256m
-# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
-
-# When configured, Gradle will run in incubating parallel mode.
-# This option should only be used with decoupled projects. More details, visit
-# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
-# org.gradle.parallel=true
-TARGET_ARCH=armeabi
-RELEASE=release
-SECURED=1
-ERROR_MSG="if building examples from android-studio, you might need to modify the default TARGET_ARCH\
- and RELEASE in <iotivity>/android/examples/gradle.properties,\
- if your aar file has different values for TARGET_ARCH and RELEASE"
-
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2016 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 ':app'
+++ /dev/null
-#//******************************************************************
-#//
-#// Copyright 2016 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.
-#//
-#//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-import os
-import platform
-Import('env')
-
-android_home = env.get('ANDROID_HOME')
-
-ANDROID_TARGET_ARCH = env.get('TARGET_ARCH')
-if env.get('RELEASE'):
- ANDROID_RELEASE="release"
-else:
- ANDROID_RELEASE="debug"
-
-os.environ['ANDROID_HOME'] = env.get('ANDROID_HOME')
-os.environ['ANDROID_NDK_HOME'] = env.get('ANDROID_NDK')
-
-if not os.path.exists(android_home + '/platforms/android-21') or not os.path.exists(android_home + '/build-tools/20.0.0'):
- print '''
-***************************************** Info ********************************
-* Either 'Android API 21' is not installed or 'Android SDK Build Tools *
-* 20.0.0' is not installed. The Android SDK Manager will now open. Please *
-* be sure to deselect all options, then select the following 2 packages: *
-* 1. Under "Tools" select "Android SDK Build-tools" Revision 20. *
-* 2. Under "Android 5.0.1 (API 21)" select "SDK Platform" *
-* 3. Continue by selecting "Install 2 Packages" *
-* *
-* NOTE: If you have an http proxy, please press ctrl+c now and edit/create *
-* the following file in your $HOME directory as follows: *
-* *
-* Edit/Create file: "$HOME/.android/androidtool.cfg" *
-* *
-* http.proxyPort=<YOUR_PORT_NUMBER> *
-* sdkman.monitor.density=108 *
-* http.proxyHost=<YOUR_HTTP_PROXY_ADDRESS> *
-* sdkman.show.update.only=true *
-* sdkman.ask.adb.restart=false *
-* sdkman.force.http=true *
-* sdkman.show.updateonly=true *
-* *
-*******************************************************************************
-
-...Opening Android SDK Manager now. Once you are finished, the build will continue.
-'''
- os.system(android_home + '/tools/android')
-
-#SConscript("../../../../../../android/android_api/SConscript")
-
-def ensure_libs(target, source, env):
- return target, [source, env.get('BUILD_DIR') + 'liboc.so', env.get('BUILD_DIR') + 'liboc_logger.so']
-
-jdk_env = Environment(ENV=os.environ)
-jdk_env['BUILDERS']['Gradle'] = Builder(action = env.get('ANDROID_GRADLE') +
- ' build -bservice/easy-setup/sampleapp/mediator/android/EasySetup/build.gradle -PTARGET_ARCH=%s -PRELEASE=%s --stacktrace' %(ANDROID_TARGET_ARCH, ANDROID_RELEASE),
- emitter = ensure_libs)
-jdk_env['BUILD_DIR'] = env.get('BUILD_DIR')
-cmdBuildEasysetupApp=jdk_env.Gradle(target="EasySetup/app/apk",
- source="EasySetup/app/src/main/java/org/iotivity/service/easysetup/EasysetupActivity.java")
-
-Depends(cmdBuildEasysetupApp, env.get('easysetupAAR'))
\ No newline at end of file
+++ /dev/null
-import os
-import platform
-Import('env')
-
-android_home = env.get('ANDROID_HOME')
-
-ANDROID_TARGET_ARCH = env.get('TARGET_ARCH')
-if env.get('RELEASE'):
- ANDROID_RELEASE="release"
-else:
- ANDROID_RELEASE="debug"
-
-os.environ['ANDROID_HOME'] = env.get('ANDROID_HOME')
-os.environ['ANDROID_NDK_HOME'] = env.get('ANDROID_NDK')
-
-if not os.path.exists(android_home + '/platforms/android-21') or not os.path.exists(android_home + '/build-tools/20.0.0'):
- print '''
-***************************************** Info ********************************
-* Either 'Android API 21' is not installed or 'Android SDK Build Tools *
-* 20.0.0' is not installed. The Android SDK Manager will now open. Please *
-* be sure to deselect all options, then select the following 2 packages: *
-* 1. Under "Tools" select "Android SDK Build-tools" Revision 20. *
-* 2. Under "Android 5.0.1 (API 21)" select "SDK Platform" *
-* 3. Continue by selecting "Install 2 Packages" *
-* *
-* NOTE: If you have an http proxy, please press ctrl+c now and edit/create *
-* the following file in your $HOME directory as follows: *
-* *
-* Edit/Create file: "$HOME/.android/androidtool.cfg" *
-* *
-* http.proxyPort=<YOUR_PORT_NUMBER> *
-* sdkman.monitor.density=108 *
-* http.proxyHost=<YOUR_HTTP_PROXY_ADDRESS> *
-* sdkman.show.update.only=true *
-* sdkman.ask.adb.restart=false *
-* sdkman.force.http=true *
-* sdkman.show.updateonly=true *
-* *
-*******************************************************************************
-
-...Opening Android SDK Manager now. Once you are finished, the build will continue.
-'''
- os.system(android_home + '/tools/android')
-
-
-def ensure_libs(target, source, env):
- return target, [source, env.get('BUILD_DIR') + 'liboc.so',
- env.get('BUILD_DIR') + 'liboc_logger.so',
- env.get('BUILD_DIR') + 'libnotification_provider_wrapper.so',
- env.get('BUILD_DIR') + 'libnotification_consumer_wrapper.so']
-
-
-jdk_env = Environment(ENV=os.environ)
-jdk_env['BUILDERS']['Gradle'] = Builder(action = env.get('ANDROID_GRADLE') +
- ' build -bservice/notification/android/build.gradle -PTARGET_ARCH=%s -PRELEASE=%s --stacktrace' %(ANDROID_TARGET_ARCH, ANDROID_RELEASE),
- emitter = ensure_libs)
-jdk_env['BUILD_DIR'] = env.get('BUILD_DIR')
-cmdBuildNotification = jdk_env.Gradle(target="notification-service/objs",
- source="notification-service/src/main/java/org/iotivity/service/ns/consumer/ConsumerService.java")
-jdk_env.Clean(cmdBuildNotification, './build')
-Depends(cmdBuildNotification, env.get('baseAAR'))
-
-env.AppendUnique(notificationAAR = cmdBuildNotification)
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<module external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$" external.system.id="GRADLE" external.system.module.group="" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
- <component name="FacetManager">
- <facet type="java-gradle" name="Java-Gradle">
- <configuration>
- <option name="BUILD_FOLDER_PATH" value="$MODULE_DIR$/build" />
- </configuration>
- </facet>
- </component>
- <component name="NewModuleRootManager" inherit-compiler-output="true">
- <exclude-output />
- <content url="file://$MODULE_DIR$">
- <excludeFolder url="file://$MODULE_DIR$/.gradle" />
- </content>
- <orderEntry type="inheritedJdk" />
- <orderEntry type="sourceFolder" forTests="false" />
- </component>
-</module>
-
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-// Top-level build file where you can add configuration options common to all sub-projects/modules.
-
-buildscript {
- repositories {
- jcenter()
- }
- dependencies {
- classpath 'com.android.tools.build:gradle:1.3.0'
-
- // NOTE: Do not place your application dependencies here; they belong
- // in the individual module build.gradle files
- }
-}
-
-allprojects {
- repositories {
- jcenter {
- url "http://jcenter.bintray.com/"
- }
- }
-}
+++ /dev/null
-#
-# //******************************************************************
-# //
-# // Copyright 2015 Intel Corporation.
-# //
-# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-# //
-# // 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.
-# //
-# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#
-
-# Project-wide Gradle settings.
-
-# IDE (e.g. Android Studio) users:
-# Gradle settings configured through the IDE *will override*
-# any settings specified in this file.
-
-# For more details on how to configure your build environment visit
-# http://www.gradle.org/docs/current/userguide/build_environment.html
-
-# Specifies the JVM arguments used for the daemon process.
-# The setting is particularly useful for tweaking memory settings.
-# Default value: -Xmx10248m -XX:MaxPermSize=256m
-# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
-
-# When configured, Gradle will run in incubating parallel mode.
-# This option should only be used with decoupled projects. More details, visit
-# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
-# org.gradle.parallel=true
+++ /dev/null
-#!/usr/bin/env bash
-
-##############################################################################
-##
-## Gradle start up script for UN*X
-##
-##############################################################################
-
-# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
-DEFAULT_JVM_OPTS=""
-
-APP_NAME="Gradle"
-APP_BASE_NAME=`basename "$0"`
-
-# Use the maximum available, or set MAX_FD != -1 to use that value.
-MAX_FD="maximum"
-
-warn ( ) {
- echo "$*"
-}
-
-die ( ) {
- echo
- echo "$*"
- echo
- exit 1
-}
-
-# OS specific support (must be 'true' or 'false').
-cygwin=false
-msys=false
-darwin=false
-case "`uname`" in
- CYGWIN* )
- cygwin=true
- ;;
- Darwin* )
- darwin=true
- ;;
- MINGW* )
- msys=true
- ;;
-esac
-
-# For Cygwin, ensure paths are in UNIX format before anything is touched.
-if $cygwin ; then
- [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
-fi
-
-# Attempt to set APP_HOME
-# Resolve links: $0 may be a link
-PRG="$0"
-# Need this for relative symlinks.
-while [ -h "$PRG" ] ; do
- ls=`ls -ld "$PRG"`
- link=`expr "$ls" : '.*-> \(.*\)$'`
- if expr "$link" : '/.*' > /dev/null; then
- PRG="$link"
- else
- PRG=`dirname "$PRG"`"/$link"
- fi
-done
-SAVED="`pwd`"
-cd "`dirname \"$PRG\"`/" >&-
-APP_HOME="`pwd -P`"
-cd "$SAVED" >&-
-
-CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
-
-# Determine the Java command to use to start the JVM.
-if [ -n "$JAVA_HOME" ] ; then
- if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
- # IBM's JDK on AIX uses strange locations for the executables
- JAVACMD="$JAVA_HOME/jre/sh/java"
- else
- JAVACMD="$JAVA_HOME/bin/java"
- fi
- if [ ! -x "$JAVACMD" ] ; then
- die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
-
-Please set the JAVA_HOME variable in your environment to match the
-location of your Java installation."
- fi
-else
- JAVACMD="java"
- which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
-
-Please set the JAVA_HOME variable in your environment to match the
-location of your Java installation."
-fi
-
-# Increase the maximum file descriptors if we can.
-if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
- MAX_FD_LIMIT=`ulimit -H -n`
- if [ $? -eq 0 ] ; then
- if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
- MAX_FD="$MAX_FD_LIMIT"
- fi
- ulimit -n $MAX_FD
- if [ $? -ne 0 ] ; then
- warn "Could not set maximum file descriptor limit: $MAX_FD"
- fi
- else
- warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
- fi
-fi
-
-# For Darwin, add options to specify how the application appears in the dock
-if $darwin; then
- GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
-fi
-
-# For Cygwin, switch paths to Windows format before running java
-if $cygwin ; then
- APP_HOME=`cygpath --path --mixed "$APP_HOME"`
- CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
-
- # We build the pattern for arguments to be converted via cygpath
- ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
- SEP=""
- for dir in $ROOTDIRSRAW ; do
- ROOTDIRS="$ROOTDIRS$SEP$dir"
- SEP="|"
- done
- OURCYGPATTERN="(^($ROOTDIRS))"
- # Add a user-defined pattern to the cygpath arguments
- if [ "$GRADLE_CYGPATTERN" != "" ] ; then
- OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
- fi
- # Now convert the arguments - kludge to limit ourselves to /bin/sh
- i=0
- for arg in "$@" ; do
- CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
- CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
-
- if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
- eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
- else
- eval `echo args$i`="\"$arg\""
- fi
- i=$((i+1))
- done
- case $i in
- (0) set -- ;;
- (1) set -- "$args0" ;;
- (2) set -- "$args0" "$args1" ;;
- (3) set -- "$args0" "$args1" "$args2" ;;
- (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
- (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
- (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
- (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
- (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
- (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
- esac
-fi
-
-# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
-function splitJvmOpts() {
- JVM_OPTS=("$@")
-}
-eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
-JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
-
-exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
+++ /dev/null
-@if "%DEBUG%" == "" @echo off
-@rem ##########################################################################
-@rem
-@rem Gradle startup script for Windows
-@rem
-@rem ##########################################################################
-
-@rem Set local scope for the variables with windows NT shell
-if "%OS%"=="Windows_NT" setlocal
-
-@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
-set DEFAULT_JVM_OPTS=
-
-set DIRNAME=%~dp0
-if "%DIRNAME%" == "" set DIRNAME=.
-set APP_BASE_NAME=%~n0
-set APP_HOME=%DIRNAME%
-
-@rem Find java.exe
-if defined JAVA_HOME goto findJavaFromJavaHome
-
-set JAVA_EXE=java.exe
-%JAVA_EXE% -version >NUL 2>&1
-if "%ERRORLEVEL%" == "0" goto init
-
-echo.
-echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
-echo.
-echo Please set the JAVA_HOME variable in your environment to match the
-echo location of your Java installation.
-
-goto fail
-
-:findJavaFromJavaHome
-set JAVA_HOME=%JAVA_HOME:"=%
-set JAVA_EXE=%JAVA_HOME%/bin/java.exe
-
-if exist "%JAVA_EXE%" goto init
-
-echo.
-echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
-echo.
-echo Please set the JAVA_HOME variable in your environment to match the
-echo location of your Java installation.
-
-goto fail
-
-:init
-@rem Get command-line arguments, handling Windowz variants
-
-if not "%OS%" == "Windows_NT" goto win9xME_args
-if "%@eval[2+2]" == "4" goto 4NT_args
-
-:win9xME_args
-@rem Slurp the command line arguments.
-set CMD_LINE_ARGS=
-set _SKIP=2
-
-:win9xME_args_slurp
-if "x%~1" == "x" goto execute
-
-set CMD_LINE_ARGS=%*
-goto execute
-
-:4NT_args
-@rem Get arguments from the 4NT Shell from JP Software
-set CMD_LINE_ARGS=%$
-
-:execute
-@rem Setup the command line
-
-set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
-
-@rem Execute Gradle
-"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
-
-:end
-@rem End local scope for the variables with windows NT shell
-if "%ERRORLEVEL%"=="0" goto mainEnd
-
-:fail
-rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
-rem the _cmd.exe /c_ return code!
-if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
-exit /b 1
-
-:mainEnd
-if "%OS%"=="Windows_NT" endlocal
-
-:omega
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<module external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$/.." external.system.id="GRADLE" external.system.module.group="android_api" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
- <component name="FacetManager">
- <facet type="android-gradle" name="Android-Gradle">
- <configuration>
- <option name="GRADLE_PROJECT_PATH" value=":base" />
- </configuration>
- </facet>
- <facet type="android" name="Android">
- <configuration>
- <option name="SELECTED_BUILD_VARIANT" value="debug" />
- <option name="ASSEMBLE_TASK_NAME" value="assembleDebug" />
- <option name="COMPILE_JAVA_TASK_NAME" value="compileDebugSources" />
- <option name="ASSEMBLE_TEST_TASK_NAME" value="assembleDebugTest" />
- <option name="SOURCE_GEN_TASK_NAME" value="generateDebugSources" />
- <option name="TEST_SOURCE_GEN_TASK_NAME" value="generateDebugTestSources" />
- <option name="ALLOW_USER_CONFIGURATION" value="false" />
- <option name="MANIFEST_FILE_RELATIVE_PATH" value="/src/main/AndroidManifest.xml" />
- <option name="RES_FOLDER_RELATIVE_PATH" value="/src/main/res" />
- <option name="RES_FOLDERS_RELATIVE_PATH" value="" />
- <option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" />
- <option name="LIBRARY_PROJECT" value="true" />
- </configuration>
- </facet>
- </component>
- <component name="NewModuleRootManager" inherit-compiler-output="false">
- <output url="file://$MODULE_DIR$/build/intermediates/classes/debug" />
- <output-test url="file://$MODULE_DIR$/build/intermediates/classes/test/debug" />
- <exclude-output />
- <content url="file://$MODULE_DIR$">
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/debug" isTestSource="false" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/debug" isTestSource="false" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/debug" isTestSource="false" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/debug" isTestSource="false" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/debug" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/debug" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/test/debug" isTestSource="true" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/test/debug" isTestSource="true" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/test/debug" isTestSource="true" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/test/debug" isTestSource="true" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/test/debug" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/test/debug" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/res" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/resources" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/assets" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/aidl" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/java" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/jni" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/rs" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/res" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/assets" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/aidl" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/rs" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/res" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/resources" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/assets" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/aidl" isTestSource="true" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/java" isTestSource="true" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/jni" isTestSource="true" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/rs" isTestSource="true" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/assets" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/bundles" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/classes" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/coverage-instrumented-classes" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dependency-cache" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex-cache" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/jacoco" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/javaResources" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/libs" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/lint" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/manifests" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/ndk" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/pre-dexed" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/proguard" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/res" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/rs" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/symbols" />
- <excludeFolder url="file://$MODULE_DIR$/build/native-libs" />
- <excludeFolder url="file://$MODULE_DIR$/build/outputs" />
- <excludeFolder url="file://$MODULE_DIR$/build/tmp" />
- </content>
- <orderEntry type="jdk" jdkName="Android API 21 Platform" jdkType="Android SDK" />
- <orderEntry type="sourceFolder" forTests="false" />
- </component>
-</module>
-
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-apply plugin: 'com.android.library'
-
-android {
- compileSdkVersion 21
- buildToolsVersion "20.0.0"
- archivesBaseName = "iotivity"
-
- libraryVariants.all { variant ->
- variant.outputs.each { output ->
- def outputFile = output.outputFile
- if (outputFile != null && outputFile.name.endsWith('.aar')) {
- def fileName = "${archivesBaseName}-${TARGET_ARCH}-${outputFile.name}"
- output.outputFile = new File(outputFile.parent, fileName)
- }
- }
- }
-
- defaultConfig {
- minSdkVersion 21
- targetSdkVersion 21
- versionCode 1
- versionName "1.0"
- }
- repositories {
- flatDir {
- dirs '../../../../android/android_api/base/build/outputs/aar'
- }
- }
- buildTypes {
- release {
- proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
- }
- }
-
- lintOptions {
- abortOnError false
- }
-
- sourceSets {
- main {
- manifest.srcFile 'src/main/AndroidManifest.xml'
- jni.srcDirs = [] //disable automatic ndk-build call
- jniLibs.srcDir new File(buildDir, 'native-libs')
- }
- androidTest.setRoot('src/androidTest')
- }
-}
-
-
-dependencies {
- compile fileTree(dir: 'libs', include: ['*.jar'])
- compile ":iotivity-base-${TARGET_ARCH}-${RELEASE}@aar"
- androidTestCompile 'com.google.dexmaker:dexmaker-mockito:1.0'
- androidTestCompile 'com.google.dexmaker:dexmaker:1.0'
- androidTestCompile 'org.mockito:mockito-core:1.10.19'
-}
-
-////////////////
-////NDK Support
-////////////////
-//If using this, Android studio will fail run the following to set the environment variable for android studio:
-//launchctl setenv ANDROID_NDK_HOME
-//otherwise remove the dependsOn part and run ./gradlew buildNative from the command line
-task copyNativeLibs(type: Copy, dependsOn: 'buildNative') {
- dependsOn 'buildNative'
- from(new File('src/main/libs')) { include '**/*.so' exclude '**/libgnustl_shared.so' }
- into new File(buildDir, 'native-libs')
-}
-
-tasks.withType(JavaCompile) { compileTask -> compileTask.dependsOn copyNativeLibs }
-
-clean.dependsOn 'cleanCopyNativeLibs'
-
-tasks.withType(com.android.build.gradle.tasks.PackageApplication) {
- pkgTask ->
- pkgTask.jniFolders = new HashSet<File>()
- pkgTask.jniFolders.add(new File(buildDir, 'native-libs'))
-}
-
-task buildNative(type: Exec) {
- if (System.env.ANDROID_NDK_HOME != null) {
- //for windows use 'ndk-build.cmd'
- //def ndkBuild = new File(System.env.ANDROID_NDK_HOME, 'ndk-build.cmd')
- def ndkBuild = new File(System.env.ANDROID_NDK_HOME, 'ndk-build')
- commandLine ndkBuild, "APP_ABI=$TARGET_ARCH", "APP_OPTIM=$RELEASE", '-C', file('src/main').absolutePath
- } else {
- println '##################'
- println 'Skipping NDK build'
- println 'Reason: ANDROID_NDK_HOME not set.'
- println '##################'
- }
-}
+++ /dev/null
-# Add project specific ProGuard rules here.
-# By default, the flags in this file are appended to flags specified
-# in C:/android/sdk/tools/proguard/proguard-android.txt
-# You can edit the include path and order by changing the proguardFiles
-# directive in build.gradle.
-#
-# For more details, see
-# http://developer.android.com/guide/developing/tools/proguard.html
-
-# Add any project specific keep options here:
-
-# If your project uses WebView with JS, uncomment the following
-# and specify the fully qualified class name to the JavaScript interface
-# class:
-#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
-# public *;
-#}
+++ /dev/null
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="org.iotivity.service.ns" />
\ No newline at end of file
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2016 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.iotivity.service.ns.common;
-
-import android.util.Log;
-
-/**
- *
- * This class provides implementation of Notification MediaContents object.
- *
- */
-public class MediaContents {
-
- private static final String LOG_TAG = "NotificationService_MediaContents";
-
- private String mIconImage = null;
-
- public MediaContents(String iconImage) {
- Log.i(LOG_TAG, "MediaContents()");
- mIconImage = iconImage;
- }
-
- public String getIconImage() {
- return mIconImage;
- }
-
- public void setIconImage(String iconImage) {
- mIconImage = iconImage;
- }
-}
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2016 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.iotivity.service.ns.common;
-
-import android.util.Log;
-import org.iotivity.base.OcRepresentation;
-
-/**
- *
- * This class provides implementation of Notification Message object.
- *
- */
-public class Message {
-
- private static final String LOG_TAG = "NotificationService_Message";
-
- /**
- * This enum is used to represent different types of notification messages
- */
- public enum MessageType {
- ALERT(1),
- NOTICE(2),
- EVENT(3),
- INFO(4),
- WARNING(5);
-
- private int type;
-
- private MessageType(int type) {
- this.type = type;
- }
-
- public int getMessageType() {
- return this.type;
- }
- };
-
- private long mMessageId = 0;
- private String mProviderId = null;
-
- private String mSourceName = null;
- private MessageType mType = MessageType.ALERT;
- private String mTime = null;
- private long mTTL = 0;
- private String mTitle = null;
- private String mContentText = null;
- private MediaContents mMediaContents = null;
- private String mTopic = null;
- private OcRepresentation mExtraInfo = null;
-
- public Message(String title, String contentText, String sourceName) {
- Log.i(LOG_TAG, "Message()");
-
- mTitle = title;
- mContentText = contentText;
- mSourceName = sourceName;
- }
-
- public long getMessageId() {
- return mMessageId;
- }
-
- public String getProviderId() {
- return mProviderId;
- }
-
- public String getSourceName() {
- return mSourceName;
- }
-
- public MessageType getType() {
- return mType;
- }
-
- public String getTime() {
- return mTime;
- }
-
- public long getTTL() {
- return mTTL;
- }
-
- public String getTitle() {
- return mTitle;
- }
-
- public String getContentText() {
- return mContentText;
- }
-
- public MediaContents getMediaContents() {
- return mMediaContents;
- }
-
- public String getTopic() {
- return mTopic;
- }
-
- public OcRepresentation getExtraInfo() {
- return mExtraInfo;
- }
-
- public void setSourceName(String sourceName) {
- mSourceName = sourceName;
- }
-
- public void setType(MessageType type) {
- mType = type;
- }
-
- public void setTime(String time) {
- mTime = time;
- }
-
- public void setTTL(long ttl) {
- mTTL = ttl;
- }
-
- public void setTitle(String title) {
- mTitle = title;
- }
-
- public void setContentText(String contextText) {
- mContentText = contextText;
- }
-
- public void setMediaContents(MediaContents mediaContents) {
- mMediaContents = mediaContents;
- }
-
- public void setTopic(String topic) {
- mTopic = topic;
- }
-
- public void setExtraInfo(OcRepresentation extraInfo) {
- mExtraInfo = extraInfo;
- }
-}
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2016 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.iotivity.service.ns.common;
-
-/**
- *
- * This enum provides details of error code messages thrown in NSException.
- *
- */
-public enum NSErrorCode {
- OK("OK", ""),
- ERROR("ERROR", ""),
- SUCCESS("SUCCESS", ""),
- FAIL("FAIL", ""),
- ALLOW("ALLOW", ""),
- DENY("DENY", ""),
- JNI_EXCEPTION("JNI_EXCEPTION", "Generic Java binder error"),
- JNI_NO_NATIVE_OBJECT("JNI_NO_NATIVE_POINTER", ""),
- JNI_INVALID_VALUE("JNI_INVALID_VALUE", ""),
- NATIVE_EXCEPTION("NATIVE_EXCEPTION", "");
-
- private String error;
- private String description;
-
- private NSErrorCode(String error, String description) {
- this.error = error;
- this.description = description;
- }
-
- public String getError() {
- return error;
- }
-
- public String getDescription() {
- return description;
- }
-
- public static NSErrorCode get(String errorCode) {
- for (NSErrorCode eCode : NSErrorCode.values()) {
- if (eCode.getError().equals(errorCode)) {
- return eCode;
- }
- }
- throw new IllegalArgumentException("Unexpected NSErrorCode value");
- }
-
- @Override
- public String toString() {
- return error + (description.isEmpty() ? "" : " : " + description);
- }
-}
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2016 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.iotivity.service.ns.common;
-
-/**
- *
- * This class provides implementation of exceptions thrown by API's.
- *
- */
-public class NSException extends Exception {
-
- private NSErrorCode errorCode;
-
- public NSException(NSErrorCode errorCode, String errMessage) {
- super(errMessage + " " + errorCode.toString());
- this.errorCode = errorCode;
- }
-
- private NSException(String error, String errMessage) {
- super(errMessage + " " + error);
- this.errorCode = NSErrorCode.get(error);
- }
-
- public NSErrorCode getErrorCode() {
- return errorCode;
- }
-
- private static void addStackTrace(Throwable throwable, String file,
- String functionName, int line) {
- StackTraceElement[] stack = throwable.getStackTrace();
- StackTraceElement[] newStack = new StackTraceElement[stack.length + 1];
-
- System.arraycopy(stack, 0, newStack, 1, stack.length);
- newStack[0] = new StackTraceElement("<native>", functionName, file,
- line);
- throwable.setStackTrace(newStack);
- }
-
- private void setNativeExceptionLocation(String file, String functionName,
- int line) {
- NSException.addStackTrace(this, file, functionName, line);
- }
-}
\ No newline at end of file
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2016 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.iotivity.service.ns.common;
-
-import android.util.Log;
-
-/**
- *
- * This class provides implementation of Notification SyncInfo object.
- *
- */
-public class SyncInfo {
-
- private static final String LOG_TAG = "NotificationService_SyncInfo";
-
- /**
- * This enum is used to inform about read status of notification message
- */
- public enum SyncType {
- UNREAD(0),
- READ(1),
- DELETED(2);
-
- private int type;
-
- private SyncType(int type) {
- this.type = type;
- }
-
- public int getSyncType() {
- return this.type;
- }
- };
-
- private long mMessageId = 0;
- private String mProviderId = null;
- private SyncType mState = SyncType.UNREAD;
-
- public SyncInfo(long messageId, String providerId, SyncType state) {
- Log.i(LOG_TAG, "SyncInfo()");
-
- mMessageId = messageId;
- mProviderId = providerId;
- mState = state;
- }
-
- public long getMessageId() {
- return mMessageId;
- }
-
- public String getProviderId() {
- return mProviderId;
- }
-
- public SyncType getState() {
- return mState;
- }
-}
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2016 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.iotivity.service.ns.common;
-
-import android.util.Log;
-
-/**
- *
- * This class provides implementation of Notification Topic object.
- *
- */
-public class Topic {
-
- private static final String LOG_TAG = "NotificationService_Topic";
-
- /**
- * This enum is used to represent subscribtion status for this Topic
- * resource
- */
- public enum TopicState {
- UNSUBSCRIBED(0),
- SUBSCRIBED(1);
-
- private int type;
-
- private TopicState(int type) {
- this.type = type;
- }
-
- public int getTopicState() {
- return this.type;
- }
-
- };
-
- private String mTopicName = null;
- private TopicState mState = TopicState.UNSUBSCRIBED;
-
- public Topic(String topicName, TopicState state) {
- Log.i(LOG_TAG, "Topic()");
-
- mTopicName = topicName;
- mState = state;
- }
-
- public String getTopicName() {
- return mTopicName;
- }
-
- public void setTopicName(String topicName) {
- mTopicName = topicName;
- }
-
- public TopicState getState() {
- return mState;
- }
-
- public void setState(TopicState state) {
- mState = state;
- }
-
-}
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2016 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.iotivity.service.ns.common;
-
-import android.util.Log;
-import java.util.Vector;
-import java.util.Iterator;
-
-/**
- *
- * This class provides implementation of Topics List.
- *
- */
-public class TopicsList {
-
- private static final String LOG_TAG = "NotificationService_TopicList";
-
- private Vector<Topic> mTopicsList = new Vector<Topic>();
-
- public void addTopic(String topicname, Topic.TopicState state) {
- mTopicsList.add(new Topic(topicname, state));
- }
-
- public void removeTopic(String topicName) {
- Iterator<Topic> it = getTopicsList().iterator();
- while (it.hasNext()) {
- Topic element = it.next();
- if (element.getTopicName().equals(topicName)) {
- mTopicsList.remove(element);
- }
- }
- }
-
- public Vector<Topic> getTopicsList() {
- return mTopicsList;
- }
-
-}
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2016 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.iotivity.service.ns.consumer;
-
-import android.util.Log;
-import org.iotivity.service.ns.common.*;
-import java.util.Vector;
-
-/**
- *
- * This class provides a set of Java APIs for Notification ConsumerService.
- *
- */
-public class ConsumerService {
-
- private static final String LOG_TAG = "ConsumerService";
-
- static {
- System.loadLibrary("gnustl_shared");
- System.loadLibrary("oc_logger");
- System.loadLibrary("connectivity_abstraction");
- System.loadLibrary("ca-interface");
- System.loadLibrary("octbstack");
- System.loadLibrary("oc");
- System.loadLibrary("ocstack-jni");
- System.loadLibrary("notification_consumer");
- System.loadLibrary("notification_consumer_wrapper");
- System.loadLibrary("notification_consumer_jni");
- }
-
- private static ConsumerService instance;
- static {
- instance = new ConsumerService();
- }
-
- /**
- * API for getting instance of ConsumerService
- *
- * @return ConsumerService singleton instance created
- */
- public static ConsumerService getInstance() {
- return instance;
- }
-
- /**
- * This API will Start ConsumerService
- *
- * @param onProviderDiscoveredListener
- * OnProviderDiscoveredListener Callback Interface
- *
- * @throws NSException
- * if the parameter passed is null
- */
- public void start(OnProviderDiscoveredListener onProviderDiscoveredListener)
- throws NSException {
- nativeStart(onProviderDiscoveredListener);
- }
-
- /**
- * This API will Stop ConsumerService
- */
- public void stop() throws NSException {
- nativeStop();
- }
-
- /**
- * Request to publish resource to cloud server
- *
- * @param serverAddress
- * serverAddress combined with IP address and port number using
- * delimiter
- */
- public void enableRemoteService(String serverAddress) throws NSException {
- nativeEnableRemoteService(serverAddress);
- }
-
- /**
- * Request to subscribe to MQ server
- *
- * @param servAdd
- * servAdd combined with IP address and port number and MQ broker
- * uri using delimiter
- * @param topicName
- * the interest Topic name for subscription
- *
- * @throws NSException failed to subscribe to MQ server
- */
- public void subscribeMQService(String servAdd, String topicName)
- throws NSException {
- nativeSubscribeMQService(servAdd, topicName);
- }
-
- /**
- * This API is called to request discovery manually
- */
- public void rescanProvider() throws NSException {
- nativeRescanProvider();
- }
-
- /**
- * Interface to implement callback function to receive provider on discovery
- */
- public interface OnProviderDiscoveredListener {
-
- /**
- * Callback function to receive provider on discovery
- *
- * @param provider
- * Provider object
- */
- public void onProviderDiscovered(Provider provider);
- }
-
- private native void nativeStart(
- OnProviderDiscoveredListener onProviderDiscoveredListener)
- throws NSException;
-
- private native void nativeStop() throws NSException;
-
- private native void nativeEnableRemoteService(String serverAddress)
- throws NSException;
-
- private native void nativeSubscribeMQService(String servAdd,
- String topicName) throws NSException;
-
- private native void nativeRescanProvider() throws NSException;
-}
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2016 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.iotivity.service.ns.consumer;
-
-import android.util.Log;
-import org.iotivity.service.ns.common.*;
-import java.util.Vector;
-
-/**
- *
- * This class provides implementation of Notification Provider object.
- *
- */
-public class Provider {
-
- private static final String LOG_TAG = "ConsumerService_Provider";
-
- /**
- * Enum for defining different state of provider object
- */
- public enum ProviderState {
- ALLOW(1),
- DENY(2),
- TOPIC(3),
- STOPPED(12);
-
- private int state;
-
- private ProviderState(int state) {
- this.state = state;
- }
-
- public int getProviderState() {
- return this.state;
- }
- };
-
- private String mProviderId = null;
- private long mNativeHandle = 0;
-
- /**
- * Constructor of Provider.
- *
- * @param providerId
- * unique Id of Provider
- */
- public Provider(String providerId) {
- Log.i(LOG_TAG, "Provider()");
-
- mProviderId = providerId;
- }
-
- @Override
- protected void finalize() throws Throwable {
- try {
- nativeDispose();
- } catch (Throwable t) {
- throw t;
- } finally {
- super.finalize();
- }
- }
- /**
- * API for getting providerId
- *
- * @return ConsumerId as string
- */
- public String getProviderId() {
- return mProviderId;
- }
-
- /**
- * API for getting for getting Topic List
- *
- * @return TopicsList
- */
- public TopicsList getTopicList() throws NSException {
- return nativeGetTopicList();
- }
-
- /**
- * API for getting for getting ProviderState
- *
- * @return ProviderState
- */
- public ProviderState getProviderState() throws NSException {
- return nativeGetProviderState();
- }
-
- /**
- * API for requesting subscription of Notification service
- * This API should be called with a valid Provider object obtained from Discovery callback.
- * The API should not be called when the Provider is in STOPPED state.
- *
- * Discovery APIs to discover Providers are as below.
- * Start/rescanProvider for D2D,
- * enableRemoteService for D2S,
- *
- * @throws NSException failure to subscribe
- */
- public void subscribe() throws NSException {
- nativeSubscribe();
- }
-
- /**
- * API for requesting unsubscription of Notification service
- *
- * This API should be called with a valid Provider object obtained from Discovery callback.
- * The API should not be called when the Provider is in STOPPED state.
- *
- * @throws NSException failure to subscribe
- */
- public void unsubscribe() throws NSException {
- nativeUnsubscribe();
- }
-
- /**
- * API for requesting subscription status from Provider of Notification
- * service
- */
- public boolean isSubscribed() throws NSException {
- return nativeIsSubscribed();
- }
-
- /**
- * This method is for Sending SyncInfo of Notification service.
- *
- * @param messageId
- * unique Id of message
- * @param syncType
- * SyncType of Notification service
- */
- public void sendSyncInfo(long messageId, SyncInfo.SyncType syncType)
- throws NSException {
- nativeSendSyncInfo(messageId, syncType.ordinal());
- }
-
- /**
- * This method is for registering for listeners of Notification .
- *
- * @param onProviderStateListener
- * OnProviderStateListener callback Interface
- * @param onMessageReceivedListner
- * OnMessageReceivedListner callback Interface
- * @param onSyncInfoReceivedListner
- * OnSyncInfoReceivedListner callback Interface
- */
- public void setListener(OnProviderStateListener onProviderStateListener,
- OnMessageReceivedListener onMessageReceivedListener,
- OnSyncInfoReceivedListener onSyncInfoReceivedListener)
- throws NSException {
- nativeSetListener(onProviderStateListener, onMessageReceivedListener,
- onSyncInfoReceivedListener);
- }
-
- /**
- * Update Topic list that is wanted to be subscribed from provider
- *
- * @param topicsList
- * TopicsList of interested Topics
- *
- * @throws NSException failure to update topic list.
- */
- public void updateTopicList(TopicsList topicsList) throws NSException {
- nativeUpdateTopicList(topicsList);
- }
-
- /**
- * Interface to implement callback function to receive provider state
- * information
- */
- public interface OnProviderStateListener {
-
- /**
- * Callback function to receive provider state information
- *
- * @param state
- * ProviderState
- */
- public void onProviderStateReceived(ProviderState state);
- }
-
- /**
- * Interface to implement callback function to receive Notification Message
- */
- public interface OnMessageReceivedListener {
-
- /**
- * Callback function to receive Notification Message.
- *
- * @param message
- * Notification Message
- */
- public void onMessageReceived(Message message);
- }
-
- /**
- * Interface to implement callback function to receive message read
- * synchronization
- */
- public interface OnSyncInfoReceivedListener {
-
- /**
- * Callback function to receive message read synchronization
- *
- * @param sync
- * SyncInfo
- */
- public void onSyncInfoReceived(SyncInfo sync);
- }
-
- private native void nativeSubscribe() throws NSException;
- private native void nativeUnsubscribe() throws NSException;
-
- private native void nativeSendSyncInfo(long messageId, int syncType)
- throws NSException;
-
- private native void nativeSetListener(
- OnProviderStateListener onProviderStateListener,
- OnMessageReceivedListener onMessageReceivedListener,
- OnSyncInfoReceivedListener onSyncInfoReceivedListener)
- throws NSException;
-
- private native TopicsList nativeGetTopicList() throws NSException;
-
- private native void nativeUpdateTopicList(TopicsList topicsList)
- throws NSException;
-
- private native ProviderState nativeGetProviderState() throws NSException;
-
- private native boolean nativeIsSubscribed() throws NSException;
-
- private native void nativeDispose();
-
-}
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2016 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.iotivity.service.ns.provider;
-
-import org.iotivity.service.ns.common.*;
-import java.util.Vector;
-
-/**
- *
- * This class provides implementation of Notification Consumer object.
- *
- */
-public class Consumer {
-
- private String mConsumerId = null;
-
- /**
- * Constructor of Consumer
- */
- public Consumer(final String consumerId) {
- mConsumerId = consumerId;
- }
-
- /**
- * API for getting consumerId
- *
- * @return ConsumerId as string
- */
- public String getConsumerId() {
- return mConsumerId;
- }
-
- /**
- * API for accepting Subscription request. This function is valid only when
- * subControllability is set true.
- *
- * @param accepted
- * boolean variable representing Subscription response as
- * TRUE/FALSE.
- *
- * @throws NSException failure accepting subscription request
- */
- public void acceptSubscription(boolean accepted) throws NSException {
- nativeAcceptSubscription(mConsumerId, accepted);
- }
-
- /**
- * Select a topic for a consumer
- *
- * @param topicName
- * Topic name to select
- *
- * @throws NSException failure selecting a topic
- */
- public void setTopic(String topicName) throws NSException {
- nativeSetConsumerTopic(mConsumerId, topicName);
- }
-
- /**
- * Unselect a topic for a consumer
- *
- * @param topicName
- * Topic name to Unselect
- *
- * @throws NSException failure unselecting topic
- */
- public void unsetTopic(String topicName) throws NSException {
- nativeUnsetConsumerTopic(mConsumerId, topicName);
- }
-
- /**
- * Request topic list with selection state for the consumer
- *
- * @return Topic list
- */
- public TopicsList getConsumerTopicList() throws NSException {
- return nativeGetConsumerTopicList(mConsumerId);
- }
-
- private native void nativeAcceptSubscription(String consumerId,
- boolean accepted) throws NSException;
-
- private native void nativeSetConsumerTopic(String consumerId,
- String topicName) throws NSException;
-
- private native void nativeUnsetConsumerTopic(String consumerId,
- String topicName) throws NSException;
-
- private native TopicsList nativeGetConsumerTopicList(String consumerId)
- throws NSException;
-}
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2016 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.iotivity.service.ns.provider;
-
-import org.iotivity.service.ns.common.*;
-import java.util.Vector;
-
-/**
- *
- * This class provides a set of Java APIs for Notification ProviderService.
- *
- */
-public class ProviderService {
-
- static {
- System.loadLibrary("gnustl_shared");
- System.loadLibrary("oc_logger");
- System.loadLibrary("connectivity_abstraction");
- System.loadLibrary("ca-interface");
- System.loadLibrary("octbstack");
- System.loadLibrary("oc");
- System.loadLibrary("ocstack-jni");
- System.loadLibrary("notification_provider");
- System.loadLibrary("notification_provider_wrapper");
- System.loadLibrary("notification_provider_jni");
- }
-
- private static ProviderService instance;
-
- static {
- instance = new ProviderService();
- }
-
- /**
- * API for getting instance of ProviderService
- *
- * @return ProviderService singleton instance created
- */
- public static ProviderService getInstance() {
- return instance;
- }
-
- /**
- * Start ProviderService
- *
- * @param subscribedListener
- * OnConsumerSubscribedListener Callback
- * @param messageSynchronized
- * OnMessageSynchronizedListener Callback
- * @param subControllability
- * Set the policy for notification servcie which checks whether
- * provider is capable of denying the subscription of
- * notification message from consumer and getting controllabliity
- * to set consumer topic list. If true, provider is able to
- * control subscription request and consumer topic list.
- * Otherwise(policy is false), consumer can do the same.
- * @param userInfo
- * User defined information such as device friendly name
- * @param resourceSecurity
- * Set on/off for secure resource channel setting
- *
- * @throws NSException
- * if any callback parameter passed is null
- */
- public void start(OnConsumerSubscribedListener subscribedListener,
- OnMessageSynchronizedListener messageSynchronized,
- boolean subControllability, String userInfo,
- boolean resourceSecurity) throws NSException {
- nativeStart(subscribedListener, messageSynchronized,
- subControllability, userInfo, resourceSecurity);
- }
-
- /**
- * Stop ProviderService
- *
- * @throws NSException failed to stop ProviderService
- */
- public void stop() throws NSException {
- nativeStop();
- }
-
- /**
- * Send notification message to all subscribers
- *
- * @param message
- * Notification message including id, title, contentText
- *
- * @throws NSException failed to send notification message
- */
- public void sendMessage(Message message) throws NSException {
- nativeSendMessage(message);
- }
-
- /**
- * Send read-check to provider in order to synchronize notification status
- * with other consumers
- *
- * @param messageId
- * unique Id of Notification message to synchronize the status
- * @param syncType
- * SyncType of the SyncInfo message
- */
- public void sendSyncInfo(long messageId, SyncInfo.SyncType syncType)
- throws NSException {
- nativeSendSyncInfo(messageId, syncType.ordinal());
- }
-
- /**
- * Initialize Message class, Mandatory fields which are messge id and
- * provider(device) id are filled with
- *
- * @return Message
- */
- public Message createMessage() throws NSException {
- return nativeCreateMessage();
- }
-
- /**
- * Request to publish resource to cloud server
- *
- * @param servAdd
- * servAdd combined with IP address and port number using
- * delimiter
- *
- * @throws NSException failed to publish resource
- */
- public void enableRemoteService(String servAdd) throws NSException {
- nativeEnableRemoteService(servAdd);
- }
-
- /**
- * Request to cancel remote service using cloud server
- *
- * @param servAdd
- * servAdd combined with IP address and port number using
- * delimiter
- *
- * @throws NSException failed to publish resource
- */
- public void disableRemoteService(String servAdd) throws NSException {
- nativeDisableRemoteService(servAdd);
- }
-
- /**
- * Request to subscribe to MQ server
- *
- * @param servAdd
- * servAdd combined with IP address and port number and MQ broker
- * uri using delimiter
- * @param topicName
- * the interest Topic name for subscription
- *
- * @throws NSException failed to subscribe to MQ server
- */
- public void subscribeMQService(String servAdd, String topicName)
- throws NSException {
- nativeSubscribeMQService(servAdd, topicName);
- }
-
- /**
- * Add topic to topic list
- *
- * @param topicName
- * Topic name to add
- *
- * @throws NSException failed to add topic
- */
- public void registerTopic(String topicName) throws NSException {
- nativeRegisterTopic(topicName);
- }
-
- /**
- * Delete topic from topic list
- *
- * @param topicName
- * Topic name to add
- *
- * @throws NSException failed to delete topic
- */
- public void unregisterTopic(String topicName) throws NSException {
- nativeUnregisterTopic(topicName);
- }
-
- /**
- * Request topics list already registered by provider user
- *
- * @throws NSException failed to get topics list
- */
- public TopicsList getRegisteredTopicList() throws NSException {
- return nativeGetRegisteredTopicList();
- }
-
- /**
- * Interface to implement callback function to receive subscription request
- * of consumer
- */
- public interface OnConsumerSubscribedListener {
-
- /**
- * Callback function to receive subscription request of consumer
- *
- * @param consumer
- * Consumer who subscribes the notification message resource
- */
- public void onConsumerSubscribed(Consumer consumer);
- }
-
- /**
- * Interface to implement callback function to receive the status of the
- * message synchronization
- */
- public interface OnMessageSynchronizedListener {
-
- /**
- * Callback function to receive the status of the message
- * synchronization
- *
- * @param syncInfo
- * Synchronization information of the notification message
- */
- public void onMessageSynchronized(SyncInfo syncInfo);
- }
-
- private native void nativeStart(
- OnConsumerSubscribedListener subscribedListener,
- OnMessageSynchronizedListener messageSynchronized,
- boolean subControllability, String userInfo,
- boolean resourceSecurity) throws NSException;
-
- private native void nativeStop() throws NSException;
-
- private native void nativeSendMessage(Message message) throws NSException;
-
- private native void nativeSendSyncInfo(long messageId, int type)
- throws NSException;
-
- private native Message nativeCreateMessage() throws NSException;
-
- private native void nativeEnableRemoteService(String servAdd)
- throws NSException;
-
- private native void nativeDisableRemoteService(String servAdd)
- throws NSException;
-
- private native void nativeSubscribeMQService(String servAdd, String topicName)
- throws NSException;
-
- private native void nativeRegisterTopic(String topicName) throws NSException;
-
- private native void nativeUnregisterTopic(String topicName)
- throws NSException;
-
- private native TopicsList nativeGetRegisteredTopicList() throws NSException;
-}
+++ /dev/null
-LOCAL_PATH := $(call my-dir)
-
-ROOT_PATH := ../../../../../../..
-
-include $(CLEAR_VARS)
-OIC_LIB_PATH := $(ROOT_PATH)/out/android/$(TARGET_ARCH_ABI)/$(APP_OPTIM)
-LOCAL_MODULE := notification_consumer
-LOCAL_SRC_FILES := $(OIC_LIB_PATH)/libnotification_consumer.so
-include $(PREBUILT_SHARED_LIBRARY)
-
-include $(CLEAR_VARS)
-OIC_LIB_PATH := $(ROOT_PATH)/out/android/$(TARGET_ARCH_ABI)/$(APP_OPTIM)
-LOCAL_MODULE := notification_consumer_wrapper
-LOCAL_SRC_FILES := $(OIC_LIB_PATH)/libnotification_consumer_wrapper.so
-include $(PREBUILT_SHARED_LIBRARY)
-
-include $(CLEAR_VARS)
-OIC_LIB_PATH := $(ROOT_PATH)/android/android_api/base/libs/$(TARGET_ARCH_ABI)
-LOCAL_MODULE := android-ocstack
-LOCAL_SRC_FILES := $(OIC_LIB_PATH)/libocstack-jni.so
-include $(PREBUILT_SHARED_LIBRARY)
-
-include $(CLEAR_VARS)
-OIC_LIB_PATH := $(ROOT_PATH)/out/android/$(TARGET_ARCH_ABI)/$(APP_OPTIM)
-LOCAL_MODULE := res_directory
-LOCAL_SRC_FILES := $(OIC_LIB_PATH)/libresource_directory.so
-include $(PREBUILT_SHARED_LIBRARY)
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := notification_consumer_jni
-LOCAL_CPPFLAGS := -std=c++0x -frtti -fexceptions
-LOCAL_LDLIBS := -llog
-
-LOCAL_SHARED_LIBRARIES := ca_interface
-LOCAL_SHARED_LIBRARIES += ca
-LOCAL_SHARED_LIBRARIES += oc_logger_core
-LOCAL_SHARED_LIBRARIES += oc_logger
-LOCAL_SHARED_LIBRARIES += octbstack
-LOCAL_SHARED_LIBRARIES += oc
-LOCAL_SHARED_LIBRARIES += android-ocstack
-LOCAL_SHARED_LIBRARIES += notification_consumer
-LOCAL_SHARED_LIBRARIES += notification_consumer_wrapper
-
-OIC_SRC_DIR := ../../../../../..
-
-LOCAL_C_INCLUDES := $(OIC_SRC_DIR)/resource/csdk/stack/include
-LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/resource/csdk/logger/include
-LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/resource/include
-LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/resource/c_common
-LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/resource/c_common/oic_string/include
-LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/resource/oc_logger/include
-LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/extlibs/boost/boost_1_58_0
-LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/android/android_api/base/jni
-LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/service/notification/include
-LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/service/notification/src/common
-LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/service/notification/src/consumer
-LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/service/notification/android/notification-service/src/main/jni/common
-LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/service/notification/cpp-wrapper/common
-LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/service/notification/cpp-wrapper/consumer/inc
-
-LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/extlibs/
-
-LOCAL_SRC_FILES := consumer/JniNotificationConsumer.cpp
-LOCAL_SRC_FILES += common/JniNotificationCommon.cpp
-
-include $(BUILD_SHARED_LIBRARY)
-include $(CLEAR_VARS)
-OIC_LIB_PATH := $(ROOT_PATH)/out/android/$(TARGET_ARCH_ABI)/$(APP_OPTIM)
-LOCAL_MODULE := notification_provider_wrapper
-LOCAL_SRC_FILES := $(OIC_LIB_PATH)/libnotification_provider_wrapper.so
-include $(PREBUILT_SHARED_LIBRARY)
-
-include $(CLEAR_VARS)
-OIC_LIB_PATH := $(ROOT_PATH)/out/android/$(TARGET_ARCH_ABI)/$(APP_OPTIM)
-LOCAL_MODULE := notification_provider
-LOCAL_SRC_FILES := $(OIC_LIB_PATH)/libnotification_provider.so
-include $(PREBUILT_SHARED_LIBRARY)
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := notification_provider_jni
-LOCAL_CPPFLAGS := -std=c++0x -frtti -fexceptions
-LOCAL_LDLIBS := -llog
-
-LOCAL_SHARED_LIBRARIES := ca_interface
-LOCAL_SHARED_LIBRARIES += ca
-LOCAL_SHARED_LIBRARIES += oc_logger_core
-LOCAL_SHARED_LIBRARIES += oc_logger
-LOCAL_SHARED_LIBRARIES += octbstack
-LOCAL_SHARED_LIBRARIES += oc
-LOCAL_SHARED_LIBRARIES += android-ocstack
-LOCAL_SHARED_LIBRARIES += notification_provider
-LOCAL_SHARED_LIBRARIES += notification_provider_wrapper
-
-OIC_SRC_DIR := ../../../../../..
-
-LOCAL_C_INCLUDES := $(OIC_SRC_DIR)/resource/csdk/stack/include
-LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/resource/csdk/logger/include
-LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/resource/include
-LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/resource/c_common
-LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/resource/c_common/oic_string/include
-LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/resource/oc_logger/include
-LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/extlibs/boost/boost_1_58_0
-LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/android/android_api/base/jni
-LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/service/notification/include
-LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/service/notification/src/common
-LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/service/notification/src/provider
-LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/service/notification/android/notification-service/src/main/jni/common
-LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/service/notification/cpp-wrapper/common
-LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/service/notification/cpp-wrapper/provider/inc
-
-LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/extlibs/
-
-LOCAL_SRC_FILES := provider/JniNotificationProvider.cpp
-LOCAL_SRC_FILES += common/JniNotificationCommon.cpp
-
-include $(BUILD_SHARED_LIBRARY)
+++ /dev/null
-APP_STL:=gnustl_shared
-NDK_TOOLCHAIN_VERSION := 4.9
+++ /dev/null
-//******************************************************************\r
-//\r
-// Copyright 2016 Samsung Electronics All Rights Reserved.\r
-//\r
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
-//\r
-// Licensed under the Apache License, Version 2.0 (the "License");\r
-// you may not use this file except in compliance with the License.\r
-// You may obtain a copy of the License at\r
-//\r
-// http://www.apache.org/licenses/LICENSE-2.0\r
-//\r
-// Unless required by applicable law or agreed to in writing, software\r
-// distributed under the License is distributed on an "AS IS" BASIS,\r
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-// See the License for the specific language governing permissions and\r
-// limitations under the License.\r
-//\r
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
-\r
-#include "JniNotificationCommon.h"\r
-#include <cstddef>\r
-#include "JniUtils.h"\r
-\r
-static jclass g_cls_NSException = NULL;\r
-static jmethodID g_mid_NSException_ctor = NULL;\r
-static jmethodID g_mid_NSException_setNativeExceptionLocation = NULL;\r
-\r
-static const char *NSResultToChar(const int nsresult)\r
-{\r
- switch (nsresult)\r
- {\r
- case JNI_NS_OK:\r
- return "OK";\r
- case JNI_NS_ERROR:\r
- return "ERROR";\r
- case JNI_NS_SUCCESS:\r
- return "SUCCESS";\r
- case JNI_NS_FAIL:\r
- return "FAIL";\r
- case JNI_NS_ALLOW:\r
- return "ALLOW";\r
- case JNI_NS_DENY:\r
- return "DENY";\r
- case JNI_EXCEPTION:\r
- return "JNI_EXCEPTION";\r
- case JNI_NO_NATIVE_POINTER:\r
- return "JNI_NO_NATIVE_POINTER";\r
- case JNI_INVALID_VALUE:\r
- return "JNI_INVALID_VALUE";\r
- case NATIVE_EXCEPTION:\r
- return "NATIVE_EXCEPTION";\r
- default:\r
- return "";\r
- }\r
-}\r
-\r
-\r
-jobject getNSException(JNIEnv *env, const char *file, const char *functionName,\r
- const int line, const int code, const char *message)\r
-{\r
- NS_LOGE ("Failed : %s" , message );\r
- const char *codeChar = NSResultToChar(code);\r
- if (codeChar[0] == '\0')\r
- {\r
- codeChar = NSResultToChar(JNI_INVALID_VALUE);\r
- }\r
- jobject exception = env->NewObject(\r
- g_cls_NSException,\r
- g_mid_NSException_ctor,\r
- env->NewStringUTF(codeChar),\r
- env->NewStringUTF(message));\r
- if (!exception)\r
- {\r
- return NULL;\r
- }\r
- env->CallVoidMethod(\r
- exception,\r
- g_mid_NSException_setNativeExceptionLocation,\r
- env->NewStringUTF(file),\r
- env->NewStringUTF(functionName),\r
- line);\r
- if (env->ExceptionCheck())\r
- {\r
- return NULL;\r
- }\r
- return exception;\r
-}\r
-\r
-void throwNSException(JNIEnv *env, jobject exception)\r
-{\r
- env->Throw((jthrowable)exception);\r
-}\r
-\r
-int NSExceptionInit(JNIEnv *env)\r
-{\r
- if (!env)\r
- {\r
- NS_LOGE ("JNIEnv is null");\r
- return JNI_ERR;\r
- }\r
-\r
- //OcException\r
- jclass localNSException = env->FindClass(\r
- "org/iotivity/service/ns/common/NSException");\r
- if (!localNSException)\r
- {\r
- NS_LOGE ("Failed to get local NSException");\r
- return JNI_ERR;\r
- }\r
- g_cls_NSException = (jclass)env->NewGlobalRef(localNSException);\r
-\r
-\r
- g_mid_NSException_ctor = env->GetMethodID(g_cls_NSException,\r
- "<init>", "(Ljava/lang/String;Ljava/lang/String;)V");\r
- if (!g_mid_NSException_ctor)\r
- {\r
- NS_LOGE ("Failed to Get MethodID");\r
- return JNI_ERR;\r
- }\r
-\r
- g_mid_NSException_setNativeExceptionLocation = env->GetMethodID(g_cls_NSException,\r
- "setNativeExceptionLocation",\r
- "(Ljava/lang/String;Ljava/lang/String;I)V");\r
- if (!g_mid_NSException_setNativeExceptionLocation)\r
- {\r
- NS_LOGE ("Failed to Get MethodID");\r
- return JNI_ERR;\r
- }\r
-\r
- env->DeleteLocalRef(localNSException);\r
-\r
- return JNI_CURRENT_VERSION;\r
-}\r
+++ /dev/null
-//******************************************************************\r
-//\r
-// Copyright 2016 Samsung Electronics All Rights Reserved.\r
-//\r
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
-//\r
-// Licensed under the Apache License, Version 2.0 (the "License");\r
-// you may not use this file except in compliance with the License.\r
-// You may obtain a copy of the License at\r
-//\r
-// http://www.apache.org/licenses/LICENSE-2.0\r
-//\r
-// Unless required by applicable law or agreed to in writing, software\r
-// distributed under the License is distributed on an "AS IS" BASIS,\r
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-// See the License for the specific language governing permissions and\r
-// limitations under the License.\r
-//\r
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
-\r
-#ifndef _JNI_NOTIFICATION_COMMON_H_\r
-#define _JNI_NOTIFICATION_COMMON_H_\r
-\r
-#include <jni.h>\r
-#include <android/log.h>\r
-#include "JniSharedObjectHolder.h"\r
-\r
-\r
-#define NSTAG "NotificationService_JNI"\r
-\r
-#define JNI_CURRENT_VERSION JNI_VERSION_1_6\r
-\r
-#define NS_LOGI(...) __android_log_print(ANDROID_LOG_INFO, NSTAG, __VA_ARGS__)\r
-#define NS_LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, NSTAG, __VA_ARGS__)\r
-#define NS_LOGE(...) __android_log_print(ANDROID_LOG_ERROR, NSTAG, __VA_ARGS__)\r
-\r
-#ifdef __cplusplus\r
-extern "C" {\r
-#endif\r
-\r
-#define JNI_EXCEPTION 1000\r
-#define JNI_NO_NATIVE_POINTER 1001\r
-#define JNI_INVALID_VALUE 1002\r
-#define NATIVE_EXCEPTION 1003\r
-\r
-#define JNI_NS_OK 100\r
-#define JNI_NS_ERROR 200\r
-#define JNI_NS_SUCCESS 300\r
-#define JNI_NS_FAIL 400\r
-#define JNI_NS_ALLOW 500\r
-#define JNI_NS_DENY 600\r
-\r
-jobject getNSException(JNIEnv *env, const char *file, const char *functionName, const int line,\r
- const int code, const char *message);\r
-void throwNSException(JNIEnv *env, jobject ex);\r
-\r
-#define GetNSException(code, message) getNSException(env, __FILE__, __func__, __LINE__, code, message)\r
-#define ThrowNSException(code, message) throwNSException(env, GetNSException(code, message))\r
-\r
-static const char *NSResultToChar(const int nsresult);\r
-int NSExceptionInit(JNIEnv *env);\r
-\r
-#ifdef __cplusplus\r
-}\r
-#endif\r
-\r
-#endif // _JNI_NOTIFICATION_COMMON_H_\r
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2017 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.
- *
- ******************************************************************/
-
-#ifndef JNI_SHARED_OBJECT_HOLDER_H_
-#define JNI_SHARED_OBJECT_HOLDER_H_
-
-#include <memory>
-
-template <typename T>
-class JniSharedObjectHolder
-{
- public:
- std::shared_ptr<T> get()
- {
- return m_sharedObject;
- }
-
- static JniSharedObjectHolder *create(std::shared_ptr<T> &sharedObject)
- {
- return new JniSharedObjectHolder(sharedObject);
- }
-
- private:
- JniSharedObjectHolder(std::shared_ptr<T> &sharedObject)
- {
- m_sharedObject = sharedObject;
- }
-
- std::shared_ptr<T> m_sharedObject;
-};
-
-#endif
+++ /dev/null
-//******************************************************************\r
-//\r
-// Copyright 2016 Samsung Electronics All Rights Reserved.\r
-//\r
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
-//\r
-// Licensed under the Apache License, Version 2.0 (the "License");\r
-// you may not use this file except in compliance with the License.\r
-// You may obtain a copy of the License at\r
-//\r
-// http://www.apache.org/licenses/LICENSE-2.0\r
-//\r
-// Unless required by applicable law or agreed to in writing, software\r
-// distributed under the License is distributed on an "AS IS" BASIS,\r
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-// See the License for the specific language governing permissions and\r
-// limitations under the License.\r
-//\r
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
-\r
-#include "JniNotificationConsumer.h"\r
-#include "NSConsumerService.h"\r
-#include "NSException.h"\r
-#include "JniOcRepresentation.h"\r
-\r
-static JavaVM *g_jvm_consumer = NULL;\r
-\r
-static jobject g_obj_postListener = NULL;\r
-static jobject g_obj_syncListener = NULL;\r
-static jobject g_obj_discoverListener = NULL;\r
-static jobject g_obj_acceptListener = NULL;\r
-\r
-jclass g_cls_Message;\r
-jclass g_cls_Provider;\r
-jclass g_cls_SyncInfo;\r
-jclass g_cls_SyncType;\r
-jclass g_cls_MediaContents;\r
-jclass g_cls_TopicState;\r
-jclass g_cls_Message_Type;\r
-jclass g_cls_ProviderState;\r
-jclass g_cls_Topic;\r
-jclass g_cls_TopicsList;\r
-jclass g_cls_OcRepresentation;\r
-jmethodID g_mid_OcRepresentation_N_ctor_bool = NULL;\r
-\r
-static JNIEnv *GetJNIEnv(jint *ret)\r
-{\r
- JNIEnv *env = NULL;\r
-\r
- *ret = g_jvm_consumer->GetEnv((void **) &env, JNI_CURRENT_VERSION);\r
- switch (*ret)\r
- {\r
- case JNI_OK:\r
- return env;\r
- case JNI_EDETACHED:\r
- if (g_jvm_consumer->AttachCurrentThread(&env, NULL) != JNI_OK)\r
- {\r
- NS_LOGE ("Failed to get the environment");\r
- return NULL;\r
- }\r
- else\r
- {\r
- return env;\r
- }\r
- case JNI_EVERSION:\r
- NS_LOGE ("JNI version is not supported");\r
- return NULL;\r
- default:\r
- NS_LOGE ("Failed to get the environment");\r
- return NULL;\r
- }\r
-}\r
-\r
-jobject getJavaProviderState(JNIEnv *env, OIC::Service::NSProviderState state)\r
-{\r
- NS_LOGD ("ConsumerService_getJavaProviderState - IN");\r
- jobject providerState = NULL;\r
- switch (state)\r
- {\r
- case OIC::Service::NSProviderState::ALLOW:\r
- {\r
- static jfieldID fieldID = env->GetStaticFieldID(g_cls_ProviderState,\r
- "ALLOW", "Lorg/iotivity/service/ns/consumer/Provider$ProviderState;");\r
- providerState = env->GetStaticObjectField(g_cls_ProviderState, fieldID);\r
- break;\r
- }\r
- case OIC::Service::NSProviderState::DENY:\r
- {\r
- static jfieldID fieldID = env->GetStaticFieldID(g_cls_ProviderState,\r
- "DENY", "Lorg/iotivity/service/ns/consumer/Provider$ProviderState;");\r
- providerState = env->GetStaticObjectField(g_cls_ProviderState, fieldID);\r
- break;\r
- }\r
- case OIC::Service::NSProviderState::TOPIC:\r
- {\r
- static jfieldID fieldID = env->GetStaticFieldID(g_cls_ProviderState,\r
- "TOPIC", "Lorg/iotivity/service/ns/consumer/Provider$ProviderState;");\r
- providerState = env->GetStaticObjectField(g_cls_ProviderState, fieldID);\r
- break;\r
- }\r
- case OIC::Service::NSProviderState::STOPPED:\r
- {\r
- static jfieldID fieldID = env->GetStaticFieldID(g_cls_ProviderState,\r
- "STOPPED", "Lorg/iotivity/service/ns/consumer/Provider$ProviderState;");\r
- providerState = env->GetStaticObjectField(g_cls_ProviderState, fieldID);\r
- break;\r
- }\r
- default:\r
- {\r
- providerState = NULL;\r
- break;\r
- }\r
- }\r
- NS_LOGD ("ConsumerService_getJavaProviderState - OUT");\r
- return providerState;\r
-}\r
-\r
-jobject getJavaSyncType(JNIEnv *env, OIC::Service::NSSyncInfo::NSSyncType nsType)\r
-{\r
- NS_LOGD ("ConsumerService_getJavaSyncType - IN");\r
-\r
- // SyncType\r
- jclass cls_SyncType = (jclass) (env->NewLocalRef(g_cls_SyncType));\r
- if (!cls_SyncType)\r
- {\r
- NS_LOGE ("Failed to Get ObjectClass for SyncType");\r
- return NULL;\r
- }\r
- jobject syncType = NULL;\r
- switch (nsType)\r
- {\r
- case OIC::Service::NSSyncInfo::NSSyncType::NS_SYNC_UNREAD:\r
- {\r
- static jfieldID fieldID = env->GetStaticFieldID(cls_SyncType,\r
- "UNREAD", "Lorg/iotivity/service/ns/common/SyncInfo$SyncType;");\r
- syncType = env->GetStaticObjectField(cls_SyncType, fieldID);\r
- break;\r
- }\r
- case OIC::Service::NSSyncInfo::NSSyncType::NS_SYNC_READ :\r
- {\r
- static jfieldID fieldID = env->GetStaticFieldID(cls_SyncType,\r
- "READ", "Lorg/iotivity/service/ns/common/SyncInfo$SyncType;");\r
- syncType = env->GetStaticObjectField(cls_SyncType, fieldID);\r
- break;\r
- }\r
- case OIC::Service::NSSyncInfo::NSSyncType::NS_SYNC_DELETED :\r
- {\r
- static jfieldID fieldID = env->GetStaticFieldID(cls_SyncType,\r
- "DELETED", "Lorg/iotivity/service/ns/common/SyncInfo$SyncType;");\r
- syncType = env->GetStaticObjectField(cls_SyncType, fieldID);\r
- break;\r
- }\r
- default:\r
- {\r
- syncType = NULL;\r
- break;\r
- }\r
- }\r
-\r
- NS_LOGD ("ConsumerService_getJavaSyncType - OUT");\r
- return syncType;\r
-}\r
-\r
-jobject getJavaTopicState(JNIEnv *env, OIC::Service::NSTopic::NSTopicState nsState)\r
-{\r
- NS_LOGD ("ConsumerService_getJavaTopicState - IN");\r
-\r
- // TopicState\r
- jclass cls_topicState = (jclass) (env->NewLocalRef(g_cls_TopicState));\r
- if (!cls_topicState)\r
- {\r
- NS_LOGE ("Failed to Get ObjectClass for TopicState Type");\r
- return NULL;\r
- }\r
- jobject topicState = NULL;\r
-\r
- switch (nsState)\r
- {\r
- case OIC::Service::NSTopic::NSTopicState::UNSUBSCRIBED:\r
- {\r
- static jfieldID fieldID = env->GetStaticFieldID(cls_topicState,\r
- "UNSUBSCRIBED", "Lorg/iotivity/service/ns/common/Topic$TopicState;");\r
- topicState = env->GetStaticObjectField(cls_topicState, fieldID);\r
- break;\r
- }\r
- case OIC::Service::NSTopic::NSTopicState::SUBSCRIBED:\r
- {\r
- static jfieldID fieldID = env->GetStaticFieldID(cls_topicState,\r
- "SUBSCRIBED", "Lorg/iotivity/service/ns/common/Topic$TopicState;");\r
- topicState = env->GetStaticObjectField(cls_topicState, fieldID);\r
- break;\r
- }\r
- default:\r
- {\r
- topicState = NULL;\r
- break;\r
- }\r
- }\r
-\r
- NS_LOGD ("ConsumerService_getJavaTopicState - OUT");\r
- return topicState;\r
-}\r
-\r
-jobject getJavaTopicsList(JNIEnv *env, std::shared_ptr<OIC::Service::NSTopicsList> topicList)\r
-{\r
- NS_LOGD ("ConsumerService_getJavaTopicsList - IN");\r
- jclass cls_topicList = (jclass) (env->NewLocalRef(g_cls_TopicsList));\r
- if (!cls_topicList)\r
- {\r
- NS_LOGE ("Failed to Get ObjectClass for TopicsList");\r
- return NULL;\r
- }\r
- jmethodID mid_topicList = env->GetMethodID(cls_topicList, "<init>", "()V");\r
- if (!mid_topicList)\r
- {\r
- NS_LOGE ("Failed to Get MethodID for TopicsList<init>");\r
- return NULL;\r
- }\r
- jobject obj_topicList = env->NewObject(cls_topicList, mid_topicList);\r
- if (!obj_topicList)\r
- {\r
- NS_LOGE ("Failed to Get object for TopicsList");\r
- return NULL;\r
- }\r
- jmethodID mid_addTopic = env->GetMethodID(cls_topicList, "addTopic",\r
- "(Ljava/lang/String;Lorg/iotivity/service/ns/common/Topic$TopicState;)V");\r
- if (!mid_addTopic)\r
- {\r
- NS_LOGE ("Failed to Get MethodID for addTopic");\r
- return NULL;\r
- }\r
- for (auto it : topicList->getTopicsList())\r
- {\r
- jobject jState = getJavaTopicState(env, it.getState());\r
- std::string topicName = it.getTopicName();\r
- jstring jTopicName = env->NewStringUTF(topicName.c_str());\r
- env->CallVoidMethod(obj_topicList, mid_addTopic, jTopicName, jState);\r
- }\r
- env->DeleteLocalRef(cls_topicList);\r
- NS_LOGD ("ConsumerService_getJavaTopicsList - OUT");\r
- return obj_topicList;\r
-}\r
-\r
-bool getNativeTopicState(JNIEnv *env, jobject jTopic , OIC::Service::NSTopic::NSTopicState &state )\r
-{\r
- NS_LOGD ("ConsumerService_getNativeTopicState - IN");\r
-\r
- jclass cls_topic = env->GetObjectClass( jTopic);\r
- // TopicState\r
- jclass cls_TopicState = (jclass) (env->NewLocalRef(g_cls_TopicState));\r
- if (!cls_TopicState)\r
- {\r
- NS_LOGE ("Failed to Get ObjectClass for cls_TopicState Type");\r
- return false;\r
- }\r
- jmethodID mid = env->GetMethodID(cls_TopicState, "ordinal", "()I");\r
- jfieldID fid_state = env->GetFieldID( cls_topic, "mState",\r
- "Lorg/iotivity/service/ns/common/Topic$TopicState;");\r
- if (fid_state == NULL)\r
- {\r
- NS_LOGE ("Error: jfieldID for state type is null");\r
- return false;\r
- }\r
- jobject jobj = env->GetObjectField( jTopic, fid_state);\r
- if (jobj == NULL)\r
- {\r
- NS_LOGE ("Error: object of field state Type is null");\r
- return false;\r
- }\r
- jint jState = env->CallIntMethod(jobj, mid);\r
- state = (OIC::Service::NSTopic::NSTopicState) jState;\r
- NS_LOGD ("ConsumerService_getNativeTopicState - OUT");\r
- return true;\r
-\r
-}\r
-\r
-const char *getNativeTopicName(JNIEnv *env, jobject jTopic)\r
-{\r
- NS_LOGD ("ConsumerService_getNativeTopicName - IN");\r
- jclass cls_topic = env->GetObjectClass( jTopic);\r
- if (cls_topic == NULL)\r
- {\r
- NS_LOGE ("Error: Class for Topic is null");\r
- return nullptr;\r
- }\r
- jfieldID fid_name = env->GetFieldID( cls_topic, "mTopicName", "Ljava/lang/String;");\r
- if (fid_name == NULL)\r
- {\r
- NS_LOGE ("Error: jfieldID for Topic Name is null");\r
- return nullptr;\r
- }\r
- jstring jTopicName = (jstring) env->GetObjectField( jTopic, fid_name);\r
- const char *topicName = NULL;\r
- if (jTopicName)\r
- {\r
- topicName = env->GetStringUTFChars( jTopicName, NULL);\r
- }\r
- else\r
- {\r
- NS_LOGI (TAG, "Info: topicName is null");\r
- }\r
- NS_LOGD ("ConsumerService_getNativeTopicName - OUT");\r
- return topicName;\r
-\r
-}\r
-\r
-std::shared_ptr<OIC::Service::NSTopicsList> getNativeTopicsList(JNIEnv *env, jobject jTopicList)\r
-{\r
- NS_LOGD ("ConsumerService_getNativeTopicsList - IN");\r
-\r
- jclass cls_topicList = env->GetObjectClass( jTopicList);\r
- if (cls_topicList == NULL)\r
- {\r
- NS_LOGE ("Error: Class for Topic List is null");\r
- return nullptr;\r
- }\r
- jfieldID fid_list = env->GetFieldID( cls_topicList, "mTopicsList", "Ljava/util/Vector;");\r
- if (fid_list == NULL)\r
- {\r
- NS_LOGE ("Error: jfieldID for Topic List is null");\r
- return nullptr;\r
- }\r
- jobject jobj = env->GetObjectField( jTopicList, fid_list);\r
- if (jobj == NULL)\r
- {\r
- NS_LOGE ("Error: object of field Topic List is null");\r
- return nullptr;\r
- }\r
- jclass cls_vec = env->FindClass("java/util/Vector");\r
- if (cls_vec == NULL)\r
- {\r
- NS_LOGE ("Error: Class for Vector not found");\r
- return nullptr;\r
- }\r
- jmethodID sizeMethod = env->GetMethodID(cls_vec, "size", "()I");\r
- if (sizeMethod == NULL)\r
- {\r
- NS_LOGE ("Error: MethodId for Vector Size not found");\r
- return nullptr;\r
- }\r
- int size = env->CallIntMethod(jobj, sizeMethod);\r
- jmethodID getMethod = env->GetMethodID(cls_vec, "get", "(I)Ljava/lang/Object;");\r
- if (getMethod == NULL)\r
- {\r
- NS_LOGE ("Error: MethodId for Vector get not found");\r
- return nullptr;\r
- }\r
- std::shared_ptr<OIC::Service::NSTopicsList> nsTopicList =\r
- std::make_shared<OIC::Service::NSTopicsList>();\r
- for (int index = 0; index < size; index++)\r
- {\r
- jobject topicObj = env->CallObjectMethod(jobj, getMethod, index);\r
- if (topicObj == NULL)\r
- {\r
- NS_LOGE ("Error: object of field Topic is null");\r
- return nullptr;\r
- }\r
- const char *name = getNativeTopicName(env, topicObj);\r
- if (name == nullptr)\r
- {\r
- NS_LOGE ("Error: Couldn't find topic Name");\r
- return nullptr;\r
- }\r
- std::string topicName(name);\r
- OIC::Service::NSTopic::NSTopicState state = OIC::Service::NSTopic::NSTopicState::UNSUBSCRIBED;\r
- if (!getNativeTopicState(env, topicObj, state))\r
- {\r
- return nullptr;\r
- }\r
- nsTopicList->addTopic(topicName, state);\r
- }\r
-\r
- env->DeleteLocalRef(cls_vec);\r
- env->DeleteLocalRef(cls_topicList);\r
- NS_LOGD ("ConsumerService_getNativeTopicsList - OUT");\r
- return nsTopicList;\r
-}\r
-\r
-jobject getJavaProvider(JNIEnv *env, std::shared_ptr<OIC::Service::NSProvider> provider)\r
-{\r
- NS_LOGD ("ConsumerService_getJavaProvider - IN");\r
- NS_LOGD ("ProviderId : %s\n", provider->getProviderId().c_str());\r
-\r
- jstring jProviderId = env->NewStringUTF(provider->getProviderId().c_str());\r
- auto *objectHolder = JniSharedObjectHolder<OIC::Service::NSProvider>::create(provider);\r
- if (!objectHolder)\r
- {\r
- NS_LOGE ("Failed to create new Object Holder for Provider");\r
- return NULL;\r
- }\r
- jlong pProvider = (long)objectHolder;\r
-\r
- jclass cls_provider = (jclass) (env->NewLocalRef(g_cls_Provider));\r
- if (!cls_provider)\r
- {\r
- NS_LOGE ("Failed to Get ObjectClass for Provider");\r
- return NULL;\r
- }\r
- jmethodID mid_provider = env->GetMethodID(\r
- cls_provider, "<init>", "(Ljava/lang/String;)V");\r
- if (!mid_provider)\r
- {\r
- NS_LOGE ("Failed to Get MethodID for Provider<init>");\r
- return NULL;\r
- }\r
- jobject obj_provider = env->NewObject(cls_provider, mid_provider, jProviderId);\r
- if (!obj_provider)\r
- {\r
- NS_LOGE ("Failed to create new Object for Provider");\r
- return NULL;\r
- }\r
-\r
- jfieldID nativeHandle = env->GetFieldID(cls_provider, "mNativeHandle", "J");\r
- if (!nativeHandle)\r
- {\r
- NS_LOGE ("Failed to get nativeHandle for Provider");\r
- return NULL;\r
- }\r
- env->SetLongField(obj_provider, nativeHandle, pProvider);\r
-\r
- env->DeleteLocalRef(cls_provider);\r
- NS_LOGD ("ConsumerService_getJavaProvider - OUT");\r
- return obj_provider;\r
-}\r
-\r
-jobject getJavaMessageType(JNIEnv *env, OIC::Service::NSMessage::NSMessageType type)\r
-{\r
- NS_LOGD ("ConsumerService_getJavaMessageType - IN");\r
- jobject messageType = NULL;\r
- switch (type)\r
- {\r
- case OIC::Service::NSMessage::NSMessageType::NS_MESSAGE_ALERT:\r
- {\r
- static jfieldID fieldID = env->GetStaticFieldID(g_cls_Message_Type,\r
- "ALERT", "Lorg/iotivity/service/ns/common/Message$MessageType;");\r
- messageType = env->GetStaticObjectField(g_cls_Message_Type, fieldID);\r
- break;\r
- }\r
- case OIC::Service::NSMessage::NSMessageType::NS_MESSAGE_NOTICE:\r
- {\r
- static jfieldID fieldID = env->GetStaticFieldID(g_cls_Message_Type,\r
- "NOTICE", "Lorg/iotivity/service/ns/common/Message$MessageType;");\r
- messageType = env->GetStaticObjectField(g_cls_Message_Type, fieldID);\r
- break;\r
- }\r
- case OIC::Service::NSMessage::NSMessageType::NS_MESSAGE_EVENT:\r
- {\r
- static jfieldID fieldID = env->GetStaticFieldID(g_cls_Message_Type,\r
- "EVENT", "Lorg/iotivity/service/ns/common/Message$MessageType;");\r
- messageType = env->GetStaticObjectField(g_cls_Message_Type, fieldID);\r
- break;\r
- }\r
- case OIC::Service::NSMessage::NSMessageType::NS_MESSAGE_INFO:\r
- {\r
- static jfieldID fieldID = env->GetStaticFieldID(g_cls_Message_Type,\r
- "INFO", "Lorg/iotivity/service/ns/common/Message$MessageType;");\r
- messageType = env->GetStaticObjectField(g_cls_Message_Type, fieldID);\r
- break;\r
- }\r
- default:\r
- {\r
- messageType = NULL;\r
- break;\r
- }\r
- }\r
- NS_LOGD ("ConsumerService_getJavaMessageType - OUT");\r
- return messageType;\r
-}\r
-\r
-jobject getJavaMessage(JNIEnv *env, OIC::Service::NSMessage message)\r
-{\r
- NS_LOGD ("ConsumerService_getJavaMessage - IN");\r
-\r
- NS_LOGD ("id : %llu\n", message.getMessageId());\r
- NS_LOGD ("title : %s\n", message.getTitle().c_str());\r
- NS_LOGD ("content : %s\n", message.getContentText().c_str());\r
- NS_LOGD ("source : %s\n", message.getSourceName().c_str());\r
-\r
- jlong jMessageId = (jlong) message.getMessageId();\r
- jstring jProviderId = env->NewStringUTF(message.getProviderId().c_str());\r
- jstring jTitle = env->NewStringUTF(message.getTitle().c_str());\r
- jstring jContentText = env->NewStringUTF(message.getContentText().c_str());\r
- jstring jSourceName = env->NewStringUTF(message.getSourceName().c_str());\r
- jstring jTopic = env->NewStringUTF(message.getTopic().c_str());\r
-\r
- jstring jTime = env->NewStringUTF(message.getTime().c_str());\r
- jlong jTTL = (jlong) message.getTTL();\r
-\r
- jclass cls_message = (jclass) (env->NewLocalRef(g_cls_Message));\r
- if (!cls_message)\r
- {\r
- NS_LOGE ("Failed to Get ObjectClass for Message");\r
- return NULL ;\r
- }\r
- jmethodID mid_message = env->GetMethodID(\r
- cls_message, "<init>",\r
- "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V");\r
- if (!mid_message)\r
- {\r
- NS_LOGE ("Failed to Get MethodID for Message<init>");\r
- return NULL;\r
- }\r
- jobject obj_message = env->NewObject(cls_message, mid_message,\r
- jTitle, jContentText, jSourceName);\r
- if (!obj_message)\r
- {\r
- NS_LOGE ("Failed to Get Java Object for Message");\r
- return NULL;\r
- }\r
-\r
- jfieldID fid_messageId = env->GetFieldID(cls_message, "mMessageId", "J");\r
- if (!fid_messageId)\r
- {\r
- NS_LOGE ("Failed to get field MessageID for Message");\r
- return NULL;\r
- }\r
- env->SetLongField(obj_message, fid_messageId, jMessageId);\r
-\r
- jfieldID fid_providerId = env->GetFieldID(cls_message, "mProviderId", "Ljava/lang/String;");\r
- if (!fid_providerId)\r
- {\r
- NS_LOGE ("Failed to get field ProviderID for Message");\r
- return NULL;\r
- }\r
- env->SetObjectField(obj_message, fid_providerId, jProviderId);\r
-\r
- jfieldID fid_time = env->GetFieldID(cls_message, "mTime", "Ljava/lang/String;");\r
- if (!fid_time)\r
- {\r
- NS_LOGE ("Failed to get field Time for Message");\r
- return NULL;\r
- }\r
- env->SetObjectField(obj_message, fid_time, jTime);\r
-\r
- jfieldID fid_ttl = env->GetFieldID(cls_message, "mTTL", "J");\r
- if (!fid_ttl)\r
- {\r
- NS_LOGE ("Failed to get field TTL for Message");\r
- return NULL;\r
- }\r
- env->SetLongField(obj_message, fid_ttl, jTTL);\r
-\r
- jfieldID fid_topic = env->GetFieldID(cls_message, "mTopic", "Ljava/lang/String;");\r
- if (!fid_topic)\r
- {\r
- NS_LOGE ("Failed to get mTopic for Message");\r
- return NULL;\r
- }\r
- env->SetObjectField(obj_message, fid_topic, jTopic);\r
-\r
- OIC::Service::NSMediaContents *mediaCont = message.getMediaContents();\r
- if (mediaCont != nullptr)\r
- {\r
- jstring jIconImage = env->NewStringUTF(mediaCont->getIconImage().c_str());\r
- jclass cls_mediaContents = (jclass) (env->NewLocalRef(g_cls_MediaContents));\r
- if (!cls_mediaContents)\r
- {\r
- NS_LOGE ("Failed to Get ObjectClass for MediaContents");\r
- return NULL;\r
- }\r
- jmethodID mid_mediaContents = env->GetMethodID(\r
- cls_mediaContents, "<init>", "(Ljava/lang/String;)V");\r
- if (!mid_mediaContents)\r
- {\r
- NS_LOGE ("Failed to Get MethodID for MediaContents<init>");\r
- return NULL;\r
- }\r
- jobject obj_mediaContents = env->NewObject(cls_mediaContents, mid_mediaContents,\r
- jIconImage);\r
-\r
- jfieldID fid_mediaContents = env->GetFieldID(cls_message, "mMediaContents",\r
- "Lorg/iotivity/service/ns/common/MediaContents;");\r
- if (!fid_mediaContents)\r
- {\r
- NS_LOGE ("Failed to get field mediaContents for Message");\r
- return NULL;\r
- }\r
- env->SetObjectField(obj_message, fid_mediaContents, obj_mediaContents);\r
-\r
- }\r
-\r
- jobject jType = getJavaMessageType(env, message.getType());\r
- if (jType)\r
- {\r
- jfieldID fid_type = env->GetFieldID(cls_message, "mType",\r
- "Lorg/iotivity/service/ns/common/Message$MessageType;");\r
- if (!fid_type)\r
- {\r
- NS_LOGE ("Failed to get field Type for Message");\r
- return NULL;\r
- }\r
- env->SetObjectField(obj_message, fid_type, jType);\r
- }\r
-\r
- NS_LOGD ("Reading OCRepresentation Object from Native");\r
-\r
- OC::OCRepresentation *ocRepresentation = new OC::OCRepresentation(message.getExtraInfo());\r
- jlong handle = reinterpret_cast<jlong>(ocRepresentation);\r
- jobject jRepresentation = env->NewObject(g_cls_OcRepresentation, g_mid_OcRepresentation_N_ctor_bool,\r
- handle, true);\r
- if (!jRepresentation)\r
- {\r
- NS_LOGE ("Failed to create OcRepresentation");\r
- delete ocRepresentation;\r
- }\r
- else\r
- {\r
- NS_LOGD ("Created OCRepresentation Object from Native");\r
- }\r
- jfieldID fid_extraInfo = env->GetFieldID(cls_message, "mExtraInfo",\r
- "Lorg/iotivity/base/OcRepresentation;");\r
- if (!fid_extraInfo)\r
- {\r
- NS_LOGE ("Failed to get mExtraInfo for Message");\r
- delete ocRepresentation;\r
- return NULL;\r
- }\r
- NS_LOGD ("setting extraInfo field");\r
- env->SetObjectField(obj_message, fid_extraInfo, jRepresentation);\r
-\r
- env->DeleteLocalRef(cls_message);\r
- NS_LOGD ("ConsumerService_getJavaMessage - OUT");\r
- return obj_message;\r
-}\r
-\r
-void onDiscoverProvider(std::shared_ptr<OIC::Service::NSProvider> provider)\r
-{\r
- NS_LOGD ("ConsumerService_onDiscoverProvider - IN");\r
-\r
- jint envRet = 0;;\r
- JNIEnv *env = GetJNIEnv(&envRet);\r
- if (NULL == env)\r
- {\r
- return ;\r
- }\r
-\r
- jobject jDiscoverListener = (jobject) env->NewLocalRef(g_obj_discoverListener);\r
- if (!jDiscoverListener)\r
- {\r
- NS_LOGE ("Failed to Get jDiscoverListener");\r
- if (JNI_EDETACHED == envRet)\r
- {\r
- g_jvm_consumer->DetachCurrentThread();\r
- }\r
- return ;\r
- }\r
-\r
- jobject obj_provider = getJavaProvider(env, provider);\r
- if (!obj_provider)\r
- {\r
- NS_LOGE ("Failed to Get Provider Object");\r
- if (JNI_EDETACHED == envRet)\r
- {\r
- g_jvm_consumer->DetachCurrentThread();\r
- }\r
- return ;\r
- }\r
-\r
- jclass cls = env->GetObjectClass(jDiscoverListener);\r
- if (!cls)\r
- {\r
- NS_LOGE ("Failed to Get ObjectClass for jDiscoverListener");\r
- if (JNI_EDETACHED == envRet)\r
- {\r
- g_jvm_consumer->DetachCurrentThread();\r
- }\r
- return ;\r
- }\r
- jmethodID mid = env->GetMethodID(\r
- cls,\r
- "onProviderDiscovered",\r
- "(Lorg/iotivity/service/ns/consumer/Provider;)V");\r
- if (!mid)\r
- {\r
- NS_LOGE ("Failed to Get MethodID for onProviderDiscovered");\r
- if (JNI_EDETACHED == envRet)\r
- {\r
- g_jvm_consumer->DetachCurrentThread();\r
- }\r
- return ;\r
- }\r
-\r
- env->CallVoidMethod(jDiscoverListener, mid, obj_provider);\r
-\r
- env->DeleteLocalRef(jDiscoverListener);\r
- if (JNI_EDETACHED == envRet)\r
- {\r
- g_jvm_consumer->DetachCurrentThread();\r
- }\r
- NS_LOGD ("ConsumerService_onDiscoverProvider - OUT");\r
- return ;\r
-}\r
-\r
-void onProviderState( OIC::Service::NSProviderState state)\r
-{\r
- NS_LOGD ("ConsumerService_onProviderState -IN");\r
-\r
- jint envRet = 0;;\r
- JNIEnv *env = GetJNIEnv(&envRet);\r
- if (NULL == env)\r
- {\r
- return ;\r
- }\r
-\r
- jobject jAcceptListener = (jobject) env->NewLocalRef(g_obj_acceptListener);\r
- if (!jAcceptListener)\r
- {\r
- NS_LOGE ("Failed to Get jAcceptListener");\r
- if (JNI_EDETACHED == envRet)\r
- {\r
- g_jvm_consumer->DetachCurrentThread();\r
- }\r
- return ;\r
- }\r
- jobject obj_state = getJavaProviderState(env, state);\r
- if (!obj_state)\r
- {\r
- NS_LOGE ("Failed to Get ProviderState Object");\r
- if (JNI_EDETACHED == envRet)\r
- {\r
- g_jvm_consumer->DetachCurrentThread();\r
- }\r
- return ;\r
- }\r
-\r
- jclass cls = env->GetObjectClass(jAcceptListener);\r
- if (!cls)\r
- {\r
- NS_LOGE ("Failed to Get ObjectClass for jAcceptListener");\r
- if (JNI_EDETACHED == envRet)\r
- {\r
- g_jvm_consumer->DetachCurrentThread();\r
- }\r
- return ;\r
- }\r
- jmethodID mid = env->GetMethodID(\r
- cls,\r
- "onProviderStateReceived",\r
- "(Lorg/iotivity/service/ns/consumer/Provider$ProviderState;)V");\r
- if (!mid)\r
- {\r
- NS_LOGE ("Failed to Get MethodID for onProviderState");\r
- if (JNI_EDETACHED == envRet)\r
- {\r
- g_jvm_consumer->DetachCurrentThread();\r
- }\r
- return ;\r
- }\r
- env->CallVoidMethod(jAcceptListener, mid, obj_state);\r
-\r
- env->DeleteLocalRef(jAcceptListener);\r
- if (JNI_EDETACHED == envRet)\r
- {\r
- g_jvm_consumer->DetachCurrentThread();\r
- }\r
- NS_LOGD ("ConsumerService_onProviderState -OUT");\r
- return ;\r
-\r
-}\r
-\r
-void onMessagePosted(OIC::Service::NSMessage message)\r
-{\r
- NS_LOGD ("ConsumerService_onMessagePosted -IN");\r
-\r
- jint envRet = 0;;\r
- JNIEnv *env = GetJNIEnv(&envRet);\r
- if (NULL == env)\r
- {\r
- return ;\r
- }\r
-\r
- jobject jPostListener = (jobject) env->NewLocalRef(g_obj_postListener);\r
- if (!jPostListener)\r
- {\r
- NS_LOGE ("Failed to Get jPostListener");\r
- if (JNI_EDETACHED == envRet)\r
- {\r
- g_jvm_consumer->DetachCurrentThread();\r
- }\r
- return ;\r
- }\r
-\r
- jobject obj_message = getJavaMessage( env, message);\r
- if (!obj_message)\r
- {\r
- NS_LOGE ("Failed to Get Message Object");\r
- if (JNI_EDETACHED == envRet)\r
- {\r
- g_jvm_consumer->DetachCurrentThread();\r
- }\r
- return ;\r
- }\r
- jclass cls = env->GetObjectClass(jPostListener);\r
- if (!cls)\r
- {\r
- NS_LOGE ("Failed to Get ObjectClass for jPostListener");\r
- if (JNI_EDETACHED == envRet)\r
- {\r
- g_jvm_consumer->DetachCurrentThread();\r
- }\r
- return ;\r
- }\r
- jmethodID mid = env->GetMethodID(\r
- cls,\r
- "onMessageReceived",\r
- "(Lorg/iotivity/service/ns/common/Message;)V");\r
- if (!mid)\r
- {\r
- NS_LOGE ("Failed to Get MethodID for onMessageReceived");\r
- if (JNI_EDETACHED == envRet)\r
- {\r
- g_jvm_consumer->DetachCurrentThread();\r
- }\r
- return ;\r
- }\r
-\r
- env->CallVoidMethod(jPostListener, mid, obj_message);\r
-\r
- env->DeleteLocalRef(jPostListener);\r
- if (JNI_EDETACHED == envRet)\r
- {\r
- g_jvm_consumer->DetachCurrentThread();\r
- }\r
- NS_LOGD ("ConsumerService_onMessagePosted -OUT");\r
- return ;\r
-}\r
-\r
-void onSyncInfoReceived(OIC::Service::NSSyncInfo sync)\r
-{\r
- NS_LOGD ("ConsumerService_onSyncInfoReceived - IN");\r
-\r
- jint envRet = 0;\r
- JNIEnv *env = GetJNIEnv(&envRet);\r
- if (NULL == env)\r
- {\r
- return ;\r
- }\r
-\r
- jobject jSyncListener = (jobject) env->NewLocalRef(g_obj_syncListener);\r
- if (!jSyncListener)\r
- {\r
- NS_LOGE ("Failed to Get jSyncListener");\r
- if (JNI_EDETACHED == envRet)\r
- {\r
- g_jvm_consumer->DetachCurrentThread();\r
- }\r
- return ;\r
- }\r
-\r
- NS_LOGD ("Sync ID : %llu\n", sync.getMessageId());\r
- NS_LOGD ("Sync ProviderId : %s\n", sync.getProviderId().c_str());\r
- NS_LOGD ("Sync STATE : %d\n", (int) sync.getState());\r
-\r
- jlong jMessageId = (jlong) sync.getMessageId();\r
- jstring jProviderId = env->NewStringUTF(sync.getProviderId().c_str());\r
- jobject syncType = getJavaSyncType(env, sync.getState());\r
- if (!syncType)\r
- {\r
- NS_LOGE ("Failed to Get syncType for SyncInfo");\r
- if (JNI_EDETACHED == envRet)\r
- {\r
- g_jvm_consumer->DetachCurrentThread();\r
- }\r
- return ;\r
- }\r
- jclass cls_SyncInfo = (jclass) (env->NewLocalRef(g_cls_SyncInfo));\r
- if (!cls_SyncInfo)\r
- {\r
- NS_LOGE ("Failed to Get ObjectClass for SyncInfo");\r
- if (JNI_EDETACHED == envRet)\r
- {\r
- g_jvm_consumer->DetachCurrentThread();\r
- }\r
- return ;\r
- }\r
- jmethodID mid_syncInfo = env->GetMethodID(\r
- cls_SyncInfo,\r
- "<init>",\r
- "(JLjava/lang/String;Lorg/iotivity/service/ns/common/SyncInfo$SyncType;)V");\r
- if (!mid_syncInfo)\r
- {\r
- NS_LOGE ("Failed to Get MethodID for SyncInfo");\r
- if (JNI_EDETACHED == envRet)\r
- {\r
- g_jvm_consumer->DetachCurrentThread();\r
- }\r
- return ;\r
- }\r
-\r
- jobject obj_syncInfo = env->NewObject( cls_SyncInfo, mid_syncInfo,\r
- jMessageId, jProviderId, syncType);\r
- if (!obj_syncInfo)\r
- {\r
- NS_LOGE ("Failed to Get Object for SyncInfo");\r
- if (JNI_EDETACHED == envRet)\r
- {\r
- g_jvm_consumer->DetachCurrentThread();\r
- }\r
- return ;\r
- }\r
-\r
- jclass cls = env->GetObjectClass(jSyncListener);\r
- if (!cls)\r
- {\r
- NS_LOGE ("Failed to Get ObjectClass for jSyncListener");\r
- if (JNI_EDETACHED == envRet)\r
- {\r
- g_jvm_consumer->DetachCurrentThread();\r
- }\r
- return ;\r
- }\r
- jmethodID mid = env->GetMethodID(\r
- cls,\r
- "onSyncInfoReceived",\r
- "(Lorg/iotivity/service/ns/common/SyncInfo;)V");\r
- if (!mid)\r
- {\r
- NS_LOGE ("Failed to Get MethodID for onSyncInfoReceived");\r
- if (JNI_EDETACHED == envRet)\r
- {\r
- g_jvm_consumer->DetachCurrentThread();\r
- }\r
- return ;\r
- }\r
-\r
- env->CallVoidMethod(jSyncListener, mid, obj_syncInfo);\r
-\r
- env->DeleteLocalRef(jSyncListener);\r
- env->DeleteLocalRef(cls_SyncInfo);\r
- if (JNI_EDETACHED == envRet)\r
- {\r
- g_jvm_consumer->DetachCurrentThread();\r
- }\r
- NS_LOGD ("ConsumerService_onSyncInfoReceived - OUT");\r
- return ;\r
-}\r
-\r
-JNIEXPORT void JNICALL Java_org_iotivity_service_ns_consumer_ConsumerService_nativeStart\r
-(JNIEnv *env, jobject jObj, jobject jDiscoverListener)\r
-{\r
- NS_LOGD ("ConsumerService_StartConsumer - IN");\r
- if (!jDiscoverListener)\r
- {\r
- ThrowNSException(JNI_INVALID_VALUE, "Listener cannot be null");\r
- return;\r
- }\r
- if (g_obj_discoverListener != NULL)\r
- {\r
- env->DeleteGlobalRef(g_obj_discoverListener);\r
- }\r
- g_obj_discoverListener = (jobject) env->NewGlobalRef(jDiscoverListener);\r
-\r
- OIC::Service::NSResult result = OIC::Service::NSConsumerService::getInstance()->start(\r
- onDiscoverProvider);\r
-\r
- if (result != OIC::Service::NSResult::OK)\r
- {\r
- ThrowNSException((int) result, "Fail to start ConsumerService");\r
- return;\r
- }\r
- NS_LOGD ("ConsumerService_StartConsumer - OUT");\r
- return;\r
-\r
-}\r
-\r
-JNIEXPORT void JNICALL Java_org_iotivity_service_ns_consumer_ConsumerService_nativeStop\r
-(JNIEnv *env, jobject jObj)\r
-{\r
- NS_LOGD ("ConsumerService_StopConsumer - IN");\r
-\r
- env->DeleteGlobalRef(g_obj_postListener);\r
- env->DeleteGlobalRef(g_obj_syncListener);\r
- env->DeleteGlobalRef(g_obj_discoverListener);\r
- env->DeleteGlobalRef(g_obj_acceptListener);\r
- g_obj_postListener = NULL;\r
- g_obj_syncListener = NULL;\r
- g_obj_discoverListener = NULL;\r
- g_obj_acceptListener = NULL;\r
- OIC::Service::NSResult result = OIC::Service::NSConsumerService::getInstance()->stop();\r
-\r
- if (result != OIC::Service::NSResult::OK)\r
- {\r
- ThrowNSException((int) result, "Fail to Stop ConsumerService");\r
- return;\r
- }\r
- NS_LOGD ("ConsumerService_StopConsumer - OUT");\r
- return;\r
-}\r
-\r
-JNIEXPORT void JNICALL\r
-Java_org_iotivity_service_ns_consumer_ConsumerService_nativeEnableRemoteService\r
-(JNIEnv *env, jobject jObj, jstring jServerAddress)\r
-{\r
- NS_LOGD ("ConsumerService_EnableRemoteService - IN");\r
- if (!jServerAddress)\r
- {\r
- ThrowNSException(JNI_INVALID_VALUE, "EnableRemoteService server address NULL");\r
- return;\r
- }\r
- const char *serverAddress = env->GetStringUTFChars(jServerAddress, 0);\r
- OIC::Service::NSResult result =\r
- OIC::Service::NSConsumerService::getInstance()->enableRemoteService(std::string(serverAddress));\r
-\r
- if (result != OIC::Service::NSResult::OK)\r
- {\r
- ThrowNSException((int) result, "Fail to EnableRemoteService");\r
- return;\r
- }\r
- env->ReleaseStringUTFChars(jServerAddress, serverAddress);\r
- NS_LOGD ("ConsumerService_EnableRemoteService - OUT");\r
- return;\r
-}\r
-\r
-JNIEXPORT void JNICALL\r
-Java_org_iotivity_service_ns_consumer_ConsumerService_nativeSubscribeMQService\r
-(JNIEnv *env, jobject jObj, jstring jserverAddress, jstring jTopicName)\r
-{\r
- NS_LOGD ("ConsumerService: nativeSubscribeMQService - IN");\r
- if (!jserverAddress)\r
- {\r
- ThrowNSException(JNI_INVALID_VALUE, "Server Address Can't be NULL");\r
- return;\r
- }\r
- if (!jTopicName)\r
- {\r
- ThrowNSException(JNI_INVALID_VALUE, "TopicName Can't be NULL");\r
- return;\r
- }\r
-\r
- const char *address = env->GetStringUTFChars( jserverAddress, NULL);\r
- std::string servAddress(address);\r
- const char *topic = env->GetStringUTFChars( jTopicName, NULL);\r
- std::string topicName(topic);\r
-\r
- OIC::Service::NSResult result =\r
- OIC::Service::NSConsumerService::getInstance()->subscribeMQService(\r
- servAddress, topicName);\r
- if (result != OIC::Service::NSResult::OK)\r
- {\r
- ThrowNSException((int) result, "Fail to Subscribe to MQ Service");\r
- return;\r
- }\r
- env->ReleaseStringUTFChars(jserverAddress, address);\r
- env->ReleaseStringUTFChars(jTopicName, topic);\r
- NS_LOGD ("ConsumerService: nativeSubscribeMQService - OUT");\r
- return;\r
-}\r
-\r
-JNIEXPORT void JNICALL Java_org_iotivity_service_ns_consumer_ConsumerService_nativeRescanProvider\r
-(JNIEnv *env, jobject jObj)\r
-{\r
- NS_LOGD ("ConsumerService_RescanProvider - IN");\r
- OIC::Service::NSResult result = OIC::Service::NSConsumerService::getInstance()->rescanProvider();\r
- if (result != OIC::Service::NSResult::OK)\r
- {\r
- ThrowNSException((int) result, "Fail to RescanProvider");\r
- return;\r
- }\r
- NS_LOGD ("ConsumerService_RescanProvider - OUT");\r
- return;\r
-\r
-}\r
-\r
-JNIEXPORT void JNICALL Java_org_iotivity_service_ns_consumer_Provider_nativeSubscribe\r
-(JNIEnv *env, jobject jObj)\r
-{\r
- NS_LOGD ("Provider_Subscribe -IN");\r
- OIC::Service::NSResult result = OIC::Service::NSResult::ERROR;\r
- jclass providerClass = env->GetObjectClass(jObj);\r
- if (!providerClass)\r
- {\r
- ThrowNSException(JNI_INVALID_VALUE, "Failed to Get ObjectClass for Provider");\r
- return ;\r
- }\r
-\r
- jfieldID nativeHandle = env->GetFieldID(providerClass, "mNativeHandle", "J");\r
- if (!nativeHandle)\r
- {\r
- ThrowNSException(JNI_INVALID_VALUE, "Failed to get nativeHandle for Provider");\r
- return ;\r
- }\r
- jlong jProvider = env->GetLongField(jObj, nativeHandle);\r
- if (jProvider)\r
- {\r
- NS_LOGD ("calling subscribe on mNativeHandle");\r
- JniSharedObjectHolder<OIC::Service::NSProvider> *objectHolder =\r
- reinterpret_cast<JniSharedObjectHolder<OIC::Service::NSProvider> *>(jProvider);\r
- try\r
- {\r
- result = objectHolder->get()->subscribe();\r
- }\r
- catch (OIC::Service::NSException ex)\r
- {\r
- ThrowNSException(NATIVE_EXCEPTION, ex.what());\r
- return;\r
- }\r
- }\r
- else\r
- {\r
- NS_LOGE ("Couldn't find Provider");\r
- ThrowNSException(JNI_NO_NATIVE_POINTER, "Fail to find native Provider");\r
- }\r
- if (result != OIC::Service::NSResult::OK)\r
- {\r
- ThrowNSException((int) result, "Fail to Subscribe Provider");\r
- return;\r
- }\r
- NS_LOGD ("Provider_Subscribe -OUT");\r
- return;\r
-}\r
-\r
-JNIEXPORT void JNICALL Java_org_iotivity_service_ns_consumer_Provider_nativeUnsubscribe\r
-(JNIEnv *env, jobject jObj)\r
-{\r
- NS_LOGD ("Provider_UnSubscribe -IN");\r
- OIC::Service::NSResult result = OIC::Service::NSResult::ERROR;\r
- jclass providerClass = env->GetObjectClass(jObj);\r
- if (!providerClass)\r
- {\r
- ThrowNSException(JNI_INVALID_VALUE, "Failed to Get ObjectClass for Provider");\r
- return ;\r
- }\r
-\r
- jfieldID nativeHandle = env->GetFieldID(providerClass, "mNativeHandle", "J");\r
- if (!nativeHandle)\r
- {\r
- ThrowNSException(JNI_INVALID_VALUE, "Failed to get nativeHandle for Provider");\r
- return ;\r
- }\r
- jlong jProvider = env->GetLongField(jObj, nativeHandle);\r
- if (jProvider)\r
- {\r
- NS_LOGD ("calling subscribe on mNativeHandle");\r
- JniSharedObjectHolder<OIC::Service::NSProvider> *objectHolder =\r
- reinterpret_cast<JniSharedObjectHolder<OIC::Service::NSProvider> *>(jProvider);\r
- try\r
- {\r
- result = objectHolder->get()->unsubscribe();\r
- }\r
- catch (OIC::Service::NSException ex)\r
- {\r
- ThrowNSException(NATIVE_EXCEPTION, ex.what());\r
- return;\r
- }\r
- }\r
- else\r
- {\r
- NS_LOGE ("Couldn't find Provider");\r
- ThrowNSException(JNI_NO_NATIVE_POINTER, "Fail to find native Provider");\r
- }\r
- if (result != OIC::Service::NSResult::OK)\r
- {\r
- ThrowNSException((int) result, "Fail to UnSubscribe Provider");\r
- return;\r
- }\r
- NS_LOGD ("Provider_UnSubscribe -OUT");\r
- return;\r
-}\r
-\r
-JNIEXPORT void JNICALL Java_org_iotivity_service_ns_consumer_Provider_nativeSendSyncInfo\r
-(JNIEnv *env, jobject jObj, jlong jMessageId, jint jSyncType)\r
-{\r
- NS_LOGD ("Provider_SendSyncInfo - IN");\r
- OIC::Service::NSResult result = OIC::Service::NSResult::ERROR;\r
- if (!jMessageId)\r
- {\r
- ThrowNSException(JNI_INVALID_VALUE, "MessageId cannot be 0");\r
- return ;\r
- }\r
-\r
- jclass providerClass = env->GetObjectClass(jObj);\r
- if (!providerClass)\r
- {\r
- ThrowNSException(JNI_INVALID_VALUE, "Failed to Get ObjectClass for Provider");\r
- return ;\r
- }\r
-\r
- jfieldID nativeHandle = env->GetFieldID(providerClass, "mNativeHandle", "J");\r
- if (!nativeHandle)\r
- {\r
- ThrowNSException(JNI_INVALID_VALUE, "Failed to get nativeHandle for Provider");\r
- return ;\r
- }\r
- uint64_t messageId = (uint64_t) jMessageId;\r
-\r
- NS_LOGD ("!!!!!!jMessageId: %lld", jMessageId);\r
- NS_LOGD ("!!!!!!messageId: %lld", messageId);\r
-\r
- jlong jProvider = env->GetLongField(jObj, nativeHandle);\r
- if (jProvider)\r
- {\r
- NS_LOGD ("calling SendSyncInfo on mNativeHandle");\r
- JniSharedObjectHolder<OIC::Service::NSProvider> *objectHolder =\r
- reinterpret_cast<JniSharedObjectHolder<OIC::Service::NSProvider> *>(jProvider);\r
- try\r
- {\r
- result = objectHolder->get()->sendSyncInfo(messageId,\r
- (OIC::Service::NSSyncInfo::NSSyncType)jSyncType);\r
- }\r
- catch (OIC::Service::NSException ex)\r
- {\r
- ThrowNSException(NATIVE_EXCEPTION, ex.what());\r
- return;\r
- }\r
- }\r
- else\r
- {\r
- NS_LOGE ("Couldn't find Provider");\r
- ThrowNSException(JNI_NO_NATIVE_POINTER, "Fail to find native Provider");\r
- }\r
- if (result != OIC::Service::NSResult::OK)\r
- {\r
- ThrowNSException((int) result, "Fail to Send sync info");\r
- return;\r
- }\r
- NS_LOGD ("Provider_SendSyncInfo - OUT");\r
- return;\r
-}\r
-\r
-\r
-JNIEXPORT void JNICALL Java_org_iotivity_service_ns_consumer_Provider_nativeSetListener\r
-(JNIEnv *env, jobject jObj, jobject jAcceptListener, jobject jPostListener, jobject jSyncListener)\r
-{\r
- NS_LOGD ("Provider_SetListener - IN");\r
- if (!jPostListener || !jSyncListener || !jAcceptListener)\r
- {\r
- ThrowNSException(JNI_INVALID_VALUE, "Listener cannot be null");\r
- return ;\r
- }\r
-\r
- jclass providerClass = env->GetObjectClass(jObj);\r
- if (!providerClass)\r
- {\r
- ThrowNSException(JNI_INVALID_VALUE, "Failed to Get ObjectClass for Provider");\r
- return ;\r
- }\r
-\r
- jfieldID nativeHandle = env->GetFieldID(providerClass, "mNativeHandle", "J");\r
- if (!nativeHandle)\r
- {\r
- ThrowNSException(JNI_INVALID_VALUE, "Failed to get nativeHandle for Provider");\r
- return ;\r
- }\r
- jlong jProvider = env->GetLongField(jObj, nativeHandle);\r
- if (jProvider)\r
- {\r
- NS_LOGD ("calling SetListener on mNativeHandle");\r
- if (g_obj_acceptListener != NULL)\r
- {\r
- env->DeleteGlobalRef(g_obj_acceptListener);\r
- }\r
- if (g_obj_postListener != NULL)\r
- {\r
- env->DeleteGlobalRef(g_obj_postListener);\r
- }\r
- if (g_obj_syncListener != NULL)\r
- {\r
- env->DeleteGlobalRef(g_obj_syncListener);\r
- }\r
- g_obj_acceptListener = (jobject) env->NewGlobalRef(jAcceptListener);\r
- g_obj_postListener = (jobject) env->NewGlobalRef(jPostListener);\r
- g_obj_syncListener = (jobject) env->NewGlobalRef(jSyncListener);\r
-\r
- JniSharedObjectHolder<OIC::Service::NSProvider> *objectHolder =\r
- reinterpret_cast<JniSharedObjectHolder<OIC::Service::NSProvider> *>(jProvider);\r
- objectHolder->get()->setListener(onProviderState, onMessagePosted, onSyncInfoReceived);\r
- }\r
- else\r
- {\r
- NS_LOGE ("Couldn't find Provider");\r
- ThrowNSException(JNI_NO_NATIVE_POINTER, "Fail to find native Provider");\r
- }\r
- NS_LOGD ("Provider_SetListener - OUT");\r
- return;\r
-}\r
-\r
-JNIEXPORT jobject JNICALL Java_org_iotivity_service_ns_consumer_Provider_nativeGetTopicList\r
-(JNIEnv *env, jobject jObj)\r
-{\r
- NS_LOGD ("Provider_nativeGetTopicList - IN");\r
- jclass providerClass = env->GetObjectClass(jObj);\r
- if (!providerClass)\r
- {\r
- ThrowNSException(JNI_INVALID_VALUE, "Failed to Get ObjectClass for Provider");\r
- return NULL;\r
- }\r
-\r
- jfieldID nativeHandle = env->GetFieldID(providerClass, "mNativeHandle", "J");\r
- if (!nativeHandle)\r
- {\r
- ThrowNSException(JNI_INVALID_VALUE, "Failed to get nativeHandle for Provider");\r
- return NULL;\r
- }\r
- jlong jProvider = env->GetLongField(jObj, nativeHandle);\r
- std::shared_ptr<OIC::Service::NSTopicsList> topicList = nullptr;\r
- if (jProvider)\r
- {\r
- NS_LOGD ("calling subscribe on mNativeHandle");\r
- JniSharedObjectHolder<OIC::Service::NSProvider> *objectHolder =\r
- reinterpret_cast<JniSharedObjectHolder<OIC::Service::NSProvider> *>(jProvider);\r
- try\r
- {\r
- topicList = objectHolder->get()->getTopicList();\r
- }\r
- catch (OIC::Service::NSException ex)\r
- {\r
- ThrowNSException(NATIVE_EXCEPTION, ex.what());\r
- return NULL;\r
- }\r
- }\r
- else\r
- {\r
- NS_LOGE ("Couldn't find Provider");\r
- ThrowNSException(JNI_NO_NATIVE_POINTER, "Fail to find native Provider");\r
- }\r
- if (topicList == nullptr)\r
- {\r
- ThrowNSException(JNI_INVALID_VALUE, "Topic List doesn't exist");\r
- return NULL;\r
- }\r
-\r
- jobject obj_topicList = getJavaTopicsList(env, topicList);\r
-\r
- NS_LOGD ("Provider_nativeGetTopicList - OUT");\r
- return obj_topicList;\r
-}\r
-\r
-JNIEXPORT void JNICALL Java_org_iotivity_service_ns_consumer_Provider_nativeUpdateTopicList\r
-(JNIEnv *env, jobject jObj, jobject jTopicsList)\r
-{\r
- NS_LOGD ("Provider_nativeUpdateTopicList -IN");\r
- if (!jTopicsList)\r
- {\r
- ThrowNSException(JNI_INVALID_VALUE, "TopicList cannot be null");\r
- return;\r
- }\r
- std::shared_ptr<OIC::Service::NSTopicsList> nsTopicsList = getNativeTopicsList(env, jTopicsList);\r
- if (nsTopicsList == nullptr)\r
- {\r
- ThrowNSException(JNI_INVALID_VALUE, "NSTopicList cannot be created ");\r
- return;\r
- }\r
-\r
- jclass providerClass = env->GetObjectClass(jObj);\r
- if (!providerClass)\r
- {\r
- ThrowNSException(JNI_INVALID_VALUE, "Failed to Get ObjectClass for Provider");\r
- return;\r
- }\r
-\r
- jfieldID nativeHandle = env->GetFieldID(providerClass, "mNativeHandle", "J");\r
- if (!nativeHandle)\r
- {\r
- ThrowNSException(JNI_INVALID_VALUE, "Failed to get nativeHandle for Provider");\r
- return;\r
- }\r
- jlong jProvider = env->GetLongField(jObj, nativeHandle);\r
- OIC::Service::NSResult result = OIC::Service::NSResult::ERROR;\r
- if (jProvider)\r
- {\r
- NS_LOGD ("calling subscribe on mNativeHandle");\r
- JniSharedObjectHolder<OIC::Service::NSProvider> *objectHolder =\r
- reinterpret_cast<JniSharedObjectHolder<OIC::Service::NSProvider> *>(jProvider);\r
- try\r
- {\r
- result = objectHolder->get()->updateTopicList(nsTopicsList);\r
- }\r
- catch (OIC::Service::NSException ex)\r
- {\r
- ThrowNSException(NATIVE_EXCEPTION, ex.what());\r
- return;\r
- }\r
- }\r
- else\r
- {\r
- NS_LOGE ("Couldn't find Provider");\r
- ThrowNSException(JNI_NO_NATIVE_POINTER, "Fail to find native Provider");\r
- }\r
- if (result != OIC::Service::NSResult::OK)\r
- {\r
- ThrowNSException((int) result, "Fail to Update Interest Topics");\r
- return;\r
- }\r
- NS_LOGD ("Provider_nativeUpdateTopicList -OUT");\r
- return;\r
-}\r
-\r
-JNIEXPORT jobject JNICALL Java_org_iotivity_service_ns_consumer_Provider_nativeGetProviderState\r
-(JNIEnv *env, jobject jObj)\r
-{\r
- NS_LOGD ("Provider_nativeGetProviderState - IN");\r
- jclass providerClass = env->GetObjectClass(jObj);\r
- if (!providerClass)\r
- {\r
- ThrowNSException(JNI_INVALID_VALUE, "Failed to Get ObjectClass for Provider");\r
- return NULL;\r
- }\r
-\r
- jfieldID nativeHandle = env->GetFieldID(providerClass, "mNativeHandle", "J");\r
- if (!nativeHandle)\r
- {\r
- ThrowNSException(JNI_INVALID_VALUE, "Failed to get nativeHandle for Provider");\r
- return NULL;\r
- }\r
- jlong jProvider = env->GetLongField(jObj, nativeHandle);\r
- OIC::Service::NSProviderState state = OIC::Service::NSProviderState::DENY;\r
- if (jProvider)\r
- {\r
- NS_LOGD ("calling getProviderState on mNativeHandle");\r
- JniSharedObjectHolder<OIC::Service::NSProvider> *objectHolder =\r
- reinterpret_cast<JniSharedObjectHolder<OIC::Service::NSProvider> *>(jProvider);\r
- try\r
- {\r
- state = objectHolder->get()->getProviderState();\r
- }\r
- catch (OIC::Service::NSException ex)\r
- {\r
- ThrowNSException(NATIVE_EXCEPTION, ex.what());\r
- return NULL;\r
- }\r
- }\r
- else\r
- {\r
- NS_LOGE ("Couldn't find Provider");\r
- ThrowNSException(JNI_NO_NATIVE_POINTER, "Fail to find native Provider");\r
- }\r
- jobject obj_state = getJavaProviderState(env, state);\r
-\r
- NS_LOGD ("Provider_nativeGetProviderState - OUT");\r
- return obj_state;\r
-}\r
-\r
-JNIEXPORT jboolean JNICALL Java_org_iotivity_service_ns_consumer_Provider_nativeIsSubscribed\r
-(JNIEnv *env, jobject jObj)\r
-{\r
- NS_LOGD ("nativeIsSubscribed - IN");\r
- jclass providerClass = env->GetObjectClass(jObj);\r
- if (!providerClass)\r
- {\r
- ThrowNSException(JNI_INVALID_VALUE, "Failed to Get ObjectClass for Provider");\r
- return (jboolean)false;\r
- }\r
-\r
- jfieldID nativeHandle = env->GetFieldID(providerClass, "mNativeHandle", "J");\r
- if (!nativeHandle)\r
- {\r
- ThrowNSException(JNI_INVALID_VALUE, "Failed to get nativeHandle for Provider");\r
- return (jboolean)false;\r
- }\r
- jlong jProvider = env->GetLongField(jObj, nativeHandle);\r
- if (jProvider)\r
- {\r
- NS_LOGD ("calling isSubscribe on mNativeHandle");\r
- JniSharedObjectHolder<OIC::Service::NSProvider> *objectHolder =\r
- reinterpret_cast<JniSharedObjectHolder<OIC::Service::NSProvider> *>(jProvider);\r
- try\r
- {\r
- return (jboolean) objectHolder->get()->isSubscribed();\r
- }\r
- catch (OIC::Service::NSException ex)\r
- {\r
- ThrowNSException(NATIVE_EXCEPTION, ex.what());\r
- return (jboolean)false;\r
- }\r
- }\r
- else\r
- {\r
- NS_LOGE ("Couldn't find Provider");\r
- ThrowNSException(JNI_NO_NATIVE_POINTER, "Fail to find native Provider");\r
- }\r
-}\r
-\r
-JNIEXPORT void JNICALL\r
-Java_org_iotivity_service_ns_consumer_Provider_nativeDispose\r
-(JNIEnv *env, jobject object)\r
-{\r
- jclass cls_provider = (jclass) (env->NewLocalRef(g_cls_Provider));\r
- if (!cls_provider)\r
- {\r
- NS_LOGE ("Failed to Get ObjectClass for Provider");\r
- return;\r
- }\r
- jfieldID nativeHandle = env->GetFieldID(cls_provider, "mNativeHandle", "J");\r
- if (!nativeHandle)\r
- {\r
- NS_LOGE ("Failed to get nativeHandle for Provider");\r
- return;\r
- }\r
- jlong handle = env->GetLongField(object, nativeHandle);\r
- JniSharedObjectHolder<OIC::Service::NSProvider> *objectHolder =\r
- reinterpret_cast<JniSharedObjectHolder<OIC::Service::NSProvider> *>(handle);\r
- delete objectHolder;\r
- return;\r
-}\r
-\r
-// JNI OnLoad\r
-JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *jvm, void *reserved)\r
-{\r
- NS_LOGD ("ConsumerService_JNI_OnLoad");\r
- g_jvm_consumer = jvm;\r
-\r
- JNIEnv *env = NULL;\r
- if (jvm->GetEnv((void **)&env, JNI_CURRENT_VERSION) != JNI_OK)\r
- {\r
- NS_LOGE ("Failed to get the environment using GetEnv()");\r
- return JNI_ERR;\r
- }\r
-\r
- jclass localMessage = env->FindClass(\r
- "org/iotivity/service/ns/common/Message");\r
- if (!localMessage)\r
- {\r
- NS_LOGE ("Failed to get local Message class");\r
- return JNI_ERR;\r
- }\r
- g_cls_Message = (jclass) (env->NewGlobalRef(localMessage));\r
- if (!g_cls_Message)\r
- {\r
- NS_LOGE ("Failed to set Global Message reference");\r
- return JNI_ERR;\r
- }\r
-\r
- jclass localProvider = env->FindClass(\r
- "org/iotivity/service/ns/consumer/Provider");\r
- if (!localProvider)\r
- {\r
- NS_LOGE ("Failed to get local Provider class");\r
- return JNI_ERR;\r
- }\r
- g_cls_Provider = (jclass) (env->NewGlobalRef(localProvider));\r
- if (!g_cls_Provider)\r
- {\r
- NS_LOGE ("Failed to set Global Provider reference");\r
- return JNI_ERR;\r
- }\r
-\r
- jclass localSyncInfo = env->FindClass(\r
- "org/iotivity/service/ns/common/SyncInfo");\r
- if (!localSyncInfo)\r
- {\r
- NS_LOGE ("Failed to get local SyncInfo class");\r
- return JNI_ERR;\r
- }\r
- g_cls_SyncInfo = (jclass) (env->NewGlobalRef(localSyncInfo));\r
- if (!g_cls_SyncInfo)\r
- {\r
- NS_LOGE ("Failed to set Global NSSyncInfo reference");\r
- return JNI_ERR;\r
- }\r
-\r
- jclass localSyncType = env->FindClass(\r
- "org/iotivity/service/ns/common/SyncInfo$SyncType");\r
- if (!localSyncType)\r
- {\r
- NS_LOGE ("Failed to get local SyncType enum");\r
- return JNI_ERR;\r
- }\r
- g_cls_SyncType = (jclass) (env->NewGlobalRef(localSyncType));\r
- if (!g_cls_SyncType)\r
- {\r
- NS_LOGE ("Failed to set Global SyncType reference");\r
- return JNI_ERR;\r
- }\r
-\r
- jclass localMediaContents = env->FindClass(\r
- "org/iotivity/service/ns/common/MediaContents");\r
- if (!localMediaContents)\r
- {\r
- NS_LOGE ("Failed to get local MediaContents class");\r
- return JNI_ERR;\r
- }\r
- g_cls_MediaContents = (jclass) (env->NewGlobalRef(localMediaContents));\r
- if (!g_cls_MediaContents)\r
- {\r
- NS_LOGE ("Failed to set Global MediaContents reference");\r
- return JNI_ERR;\r
- }\r
- jclass localTopicState = env->FindClass(\r
- "org/iotivity/service/ns/common/Topic$TopicState");\r
- if (!localTopicState)\r
- {\r
- NS_LOGE ("Failed to get local TopicState enum");\r
- return JNI_ERR;\r
- }\r
- g_cls_TopicState = (jclass) (env->NewGlobalRef(localTopicState));\r
- if (!g_cls_TopicState)\r
- {\r
- NS_LOGE ("Failed to set Global TopicState reference");\r
- return JNI_ERR;\r
- }\r
-\r
- jclass localTopic = env->FindClass(\r
- "org/iotivity/service/ns/common/Topic");\r
- if (!localTopic)\r
- {\r
- NS_LOGE ("Failed to get local TopicState enum");\r
- return JNI_ERR;\r
- }\r
- g_cls_Topic = (jclass) (env->NewGlobalRef(localTopic));\r
- if (!g_cls_Topic)\r
- {\r
- NS_LOGE ("Failed to set Global Topic reference");\r
- return JNI_ERR;\r
- }\r
-\r
- jclass localMessageType = env->FindClass(\r
- "org/iotivity/service/ns/common/Message$MessageType");\r
- if (!localMessageType)\r
- {\r
- NS_LOGE ("Failed to get local Message Type class");\r
- return JNI_ERR;\r
- }\r
- g_cls_Message_Type = (jclass) (env->NewGlobalRef(localMessageType));\r
- if (!g_cls_Message_Type)\r
- {\r
- NS_LOGE ("Failed to set Global Message Type reference");\r
- return JNI_ERR;\r
- }\r
-\r
- jclass localProviderState = env->FindClass(\r
- "org/iotivity/service/ns/consumer/Provider$ProviderState");\r
- if (!localProviderState)\r
- {\r
- NS_LOGE ("Failed to get localProviderState Type class");\r
- return JNI_ERR;\r
- }\r
- g_cls_ProviderState = (jclass) (env->NewGlobalRef(localProviderState));\r
- if (!g_cls_ProviderState)\r
- {\r
- NS_LOGE ("Failed to set Global ProviderState Type reference");\r
- return JNI_ERR;\r
- }\r
-\r
- jclass localTopicsList = env->FindClass(\r
- "org/iotivity/service/ns/common/TopicsList");\r
- if (!localTopicsList)\r
- {\r
- NS_LOGE ("Failed to get local Topic class");\r
- return JNI_ERR;\r
- }\r
- g_cls_TopicsList = (jclass) (env->NewGlobalRef(localTopicsList));\r
- if (!g_cls_TopicsList)\r
- {\r
- NS_LOGE ("Failed to set Global TopicsList reference");\r
- return JNI_ERR;\r
- }\r
- //OcRepresentation\r
- jclass localOcRepresentation = env->FindClass("org/iotivity/base/OcRepresentation");\r
- if (!localOcRepresentation)\r
- {\r
- NS_LOGE ("Failed to get local OcRepresentation class");\r
- return JNI_ERR;\r
- }\r
- g_cls_OcRepresentation = (jclass) env->NewGlobalRef(localOcRepresentation);\r
- if (!g_cls_OcRepresentation)\r
- {\r
- NS_LOGE ("Failed to set Global OcRepresentation reference");\r
- return JNI_ERR;\r
- }\r
-\r
- g_mid_OcRepresentation_N_ctor_bool = env->GetMethodID(g_cls_OcRepresentation, "<init>", "(JZ)V");\r
- if (!g_mid_OcRepresentation_N_ctor_bool)\r
- {\r
- NS_LOGE ("Failed to get Global OcRepresentation Constructor reference");\r
- return JNI_ERR;\r
- }\r
-\r
- env->DeleteLocalRef(localMessage);\r
- env->DeleteLocalRef(localProvider);\r
- env->DeleteLocalRef(localSyncInfo);\r
- env->DeleteLocalRef(localSyncType);\r
- env->DeleteLocalRef(localMediaContents);\r
- env->DeleteLocalRef(localTopicState);\r
- env->DeleteLocalRef(localMessageType);\r
- env->DeleteLocalRef(localProviderState);\r
- env->DeleteLocalRef(localTopic);\r
- env->DeleteLocalRef(localTopicsList);\r
- env->DeleteLocalRef(localOcRepresentation);\r
-\r
- return NSExceptionInit(env);\r
-}\r
-\r
-JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *jvm, void *reserved)\r
-{\r
- NS_LOGI ("ConsumerService_JNI_OnUnload");\r
- JNIEnv *env = NULL;\r
-\r
- if (jvm->GetEnv((void **)&env, JNI_CURRENT_VERSION) != JNI_OK)\r
- {\r
- NS_LOGE ("Failed to get the environment using GetEnv()");\r
- return ;\r
- }\r
-\r
- env->DeleteGlobalRef(g_cls_Message);\r
- env->DeleteGlobalRef(g_cls_Provider);\r
- env->DeleteGlobalRef(g_cls_SyncInfo);\r
- env->DeleteGlobalRef(g_cls_SyncType);\r
- env->DeleteGlobalRef(g_cls_MediaContents);\r
- env->DeleteGlobalRef(g_cls_TopicState);\r
- env->DeleteGlobalRef(g_cls_Message_Type);\r
- env->DeleteGlobalRef(g_cls_ProviderState);\r
- env->DeleteGlobalRef(g_cls_Topic);\r
- env->DeleteGlobalRef(g_cls_TopicsList);\r
- env->DeleteGlobalRef(g_cls_OcRepresentation);\r
-}\r
+++ /dev/null
-//******************************************************************\r
-//\r
-// Copyright 2016 Samsung Electronics All Rights Reserved.\r
-//\r
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
-//\r
-// Licensed under the Apache License, Version 2.0 (the "License");\r
-// you may not use this file except in compliance with the License.\r
-// You may obtain a copy of the License at\r
-//\r
-// http://www.apache.org/licenses/LICENSE-2.0\r
-//\r
-// Unless required by applicable law or agreed to in writing, software\r
-// distributed under the License is distributed on an "AS IS" BASIS,\r
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-// See the License for the specific language governing permissions and\r
-// limitations under the License.\r
-//\r
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
-\r
-/* DO NOT EDIT THIS FILE - it is machine generated */\r
-#include "JniNotificationCommon.h"\r
-\r
-#ifndef JNI_NOTIFICATION_CONSUMER_H\r
-#define JNI_NOTIFICATION_CONSUMER_H\r
-\r
-#ifdef __cplusplus\r
-extern "C" {\r
-#endif\r
-\r
-/*\r
- * Class: org_iotivity_service_ns_consumer_ConsumerService\r
- * Method: nativeStart\r
- * Signature: (Lorg/iotivity/service/ns/consumer/ConsumerService/OnProviderDiscoveredListener;)V\r
- */\r
-JNIEXPORT void JNICALL Java_org_iotivity_service_ns_consumer_ConsumerService_nativeStart\r
-(JNIEnv *, jobject, jobject);\r
-\r
-/*\r
- * Class: org_iotivity_service_ns_consumer_ConsumerService\r
- * Method: nativeStop\r
- * Signature: ()V\r
- */\r
-JNIEXPORT void JNICALL Java_org_iotivity_service_ns_consumer_ConsumerService_nativeStop\r
-(JNIEnv *, jobject);\r
-\r
-/*\r
- * Class: org_iotivity_service_ns_consumer_ConsumerService\r
- * Method: nativeEnableRemoteService\r
- * Signature: (Ljava/lang/String;)V\r
- */\r
-JNIEXPORT void JNICALL\r
-Java_org_iotivity_service_ns_consumer_ConsumerService_nativeEnableRemoteService\r
-(JNIEnv *, jobject, jstring);\r
-\r
-/*\r
- * Class: org_iotivity_service_ns_consumer_ConsumerService\r
- * Method: nativeSubscribeMQService\r
- * Signature: (Ljava/lang/String;Ljava/lang/String;)V\r
- */\r
-JNIEXPORT void JNICALL\r
-Java_org_iotivity_service_ns_consumer_ConsumerService_nativeSubscribeMQService\r
-(JNIEnv *, jobject, jstring, jstring);\r
-\r
-/*\r
- * Class: org_iotivity_service_ns_consumer_ConsumerService\r
- * Method: nativeRescanProvider\r
- * Signature: ()V\r
- */\r
-JNIEXPORT void JNICALL Java_org_iotivity_service_ns_consumer_ConsumerService_nativeRescanProvider\r
-(JNIEnv *, jobject);\r
-\r
-/*\r
- * Class: org_iotivity_service_ns_consumer_Provider\r
- * Method: nativeSubscribe\r
- * Signature: ()V\r
- */\r
-JNIEXPORT void JNICALL Java_org_iotivity_service_ns_consumer_Provider_nativeSubscribe\r
-(JNIEnv *, jobject);\r
-\r
-\r
-/*\r
- * Class: org_iotivity_service_ns_consumer_Provider\r
- * Method: nativeUnsubscribe\r
- * Signature: ()V\r
- */\r
-JNIEXPORT void JNICALL Java_org_iotivity_service_ns_consumer_Provider_nativeUnsubscribe\r
-(JNIEnv *, jobject);\r
-\r
-/*\r
- * Class: org_iotivity_service_ns_consumer_Provider\r
- * Method: nativeSendSyncInfo\r
- * Signature: (JI)V\r
- */\r
-JNIEXPORT void JNICALL Java_org_iotivity_service_ns_consumer_Provider_nativeSendSyncInfo\r
-(JNIEnv *, jobject, jlong, jint);\r
-\r
-/*\r
- * Class: org_iotivity_service_ns_consumer_Provider\r
- * Method: nativeSetListener\r
- * Signature: (Lorg/iotivity/service/ns/consumer/Provider/OnProviderStateListener;Lorg/iotivity/service/ns/consumer/Provider/OnMessageReceivedListener;Lorg/iotivity/service/ns/consumer/Provider/OnSyncInfoReceivedListener;)V\r
- */\r
-JNIEXPORT void JNICALL Java_org_iotivity_service_ns_consumer_Provider_nativeSetListener\r
-(JNIEnv *, jobject, jobject, jobject, jobject);\r
-\r
-/*\r
- * Class: org_iotivity_service_ns_consumer_Provider\r
- * Method: nativeGetTopicList\r
- * Signature: ()Lorg/iotivity/service/ns/common/TopicsList;\r
- */\r
-JNIEXPORT jobject JNICALL Java_org_iotivity_service_ns_consumer_Provider_nativeGetTopicList\r
-(JNIEnv *, jobject);\r
-\r
-/*\r
- * Class: org_iotivity_service_ns_consumer_Provider\r
- * Method: nativeUpdateTopicList\r
- * Signature: (Lorg/iotivity/service/ns/common/TopicsList;)V\r
- */\r
-JNIEXPORT void JNICALL Java_org_iotivity_service_ns_consumer_Provider_nativeUpdateTopicList\r
-(JNIEnv *, jobject, jobject);\r
-\r
-/*\r
- * Class: org_iotivity_service_ns_consumer_Provider\r
- * Method: nativeGetProviderState\r
- * Signature: ()Lorg/iotivity/service/ns/consumer/Provider$ProviderState;\r
- */\r
-JNIEXPORT jobject JNICALL Java_org_iotivity_service_ns_consumer_Provider_nativeGetProviderState\r
-(JNIEnv *, jobject);\r
-\r
-/*\r
- * Class: org_iotivity_service_ns_consumer_Provider\r
- * Method: nativeIsSubscribed\r
- * Signature: ()Z\r
- */\r
-JNIEXPORT jboolean JNICALL Java_org_iotivity_service_ns_consumer_Provider_nativeIsSubscribed\r
-(JNIEnv *, jobject);\r
-\r
-/*\r
- * Class: org_iotivity_service_ns_consumer_Provider\r
- * Method: nativeDispose\r
- * Signature: ()V\r
- */\r
-JNIEXPORT void JNICALL Java_org_iotivity_service_ns_consumer_Provider_nativeDispose\r
-(JNIEnv *env, jobject object);\r
-\r
-#ifdef __cplusplus\r
-}\r
-#endif\r
-#endif\r
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2016 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 "JniNotificationProvider.h"
-#include "NSProviderService.h"
-#include "NSException.h"
-#include "JniOcRepresentation.h"
-
-static JavaVM *g_jvm_provider = NULL;
-
-static jobject g_obj_subscriptionListener = NULL;
-static jobject g_obj_syncListener = NULL;
-
-jclass g_cls_Message;
-jclass g_cls_Message_Type;
-jclass g_cls_Consumer;
-jclass g_cls_SyncInfo;
-jclass g_cls_SyncType;
-jclass g_cls_MediaContents;
-jclass g_cls_Topic;
-jclass g_cls_TopicsList;
-jclass g_cls_TopicState;
-jclass g_cls_OcRepresentation;
-jmethodID g_mid_OcRepresentation_N_ctor_bool = NULL;
-
-static JNIEnv *GetJNIEnv(jint *ret)
-{
- JNIEnv *env = NULL;
-
- *ret = g_jvm_provider->GetEnv((void **) &env, JNI_CURRENT_VERSION);
- switch (*ret)
- {
- case JNI_OK:
- return env;
- case JNI_EDETACHED:
- if (g_jvm_provider->AttachCurrentThread(&env, NULL) != JNI_OK)
- {
- NS_LOGE ("Failed to get the environment");
- return NULL;
- }
- else
- {
- return env;
- }
- case JNI_EVERSION:
- NS_LOGE ("JNI version is not supported");
- return NULL;
- default:
- NS_LOGE ("Failed to get the environment");
- return NULL;
- }
-}
-
-OIC::Service::NSMessage getNativeMessage(JNIEnv *env, jobject jMsg)
-{
- NS_LOGD ("JNIProviderService: getMessage - IN");
-
- jclass cls = env->GetObjectClass( jMsg);
-
- // Message type
- jclass cls_messageType = (jclass) (env->NewLocalRef(g_cls_Message_Type));
- if (!cls_messageType)
- {
- ThrowNSException(JNI_INVALID_VALUE, "Failed to Get ObjectClass for Message Type");
- return nullptr;
- }
- jmethodID mid = env->GetMethodID(cls_messageType, "ordinal", "()I");
- jfieldID fid_type = env->GetFieldID( cls, "mType",
- "Lorg/iotivity/service/ns/common/Message$MessageType;");
- if (fid_type == NULL)
- {
- ThrowNSException(JNI_INVALID_VALUE, "Error: jfieldID for message type is null");
- return nullptr;
- }
- jobject jobj = env->GetObjectField( jMsg, fid_type);
- if (jobj == NULL)
- {
- ThrowNSException(JNI_INVALID_VALUE, "Error: object of field Message Type is null");
- return nullptr;
- }
- jint jtype = env->CallIntMethod(jobj, mid);
- OIC::Service::NSMessage::NSMessageType type = (OIC::Service::NSMessage::NSMessageType) jtype;
-
- NS_LOGD ("Message Type: %ld\n", (long )type);
-
- // Message Time
- jfieldID fid_tm = env->GetFieldID( cls, "mTime", "Ljava/lang/String;");
- if (fid_tm == NULL)
- {
- ThrowNSException(JNI_INVALID_VALUE, "Error: jfieldID for message time is null");
- return nullptr;
- }
- jstring jtime = (jstring)env->GetObjectField( jMsg, fid_tm);
- const char *time = "";
- if (jtime)
- {
- time = env->GetStringUTFChars( jtime, NULL);
- }
- else
- {
- NS_LOGD ("Info: messageTitle is null");
- }
- NS_LOGD ("Message Time: %s\n", time);
-
- // Message TTL
- jfieldID fid_ttl = env->GetFieldID( cls, "mTTL", "J");
- if (fid_ttl == NULL)
- {
- ThrowNSException(JNI_INVALID_VALUE, "Error: jfieldID for message ttl is null");
- return nullptr;
- }
-
- jlong jttl = (jlong) env->GetLongField( jMsg, fid_ttl);
- uint64_t ttl = jttl;
- NS_LOGD ("TTL: %lld\n", ttl);
-
- // Message Title
- jfieldID fid_title = env->GetFieldID( cls, "mTitle", "Ljava/lang/String;");
- if (fid_title == NULL)
- {
- ThrowNSException(JNI_INVALID_VALUE, "Error: jfieldID for message title is null");
- return nullptr;
- }
- jstring jmsgTitle = (jstring)env->GetObjectField( jMsg, fid_title);
- const char *messageTitle = "";
- if (jmsgTitle)
- {
- messageTitle = env->GetStringUTFChars( jmsgTitle, NULL);
- }
- else
- {
- NS_LOGD ("Info: messageTitle is null");
- }
- NS_LOGD ("Message Title: %s\n", messageTitle);
-
- // Message Content Text
- jfieldID fid_body = env->GetFieldID( cls, "mContentText", "Ljava/lang/String;");
- if (fid_body == NULL)
- {
- ThrowNSException(JNI_INVALID_VALUE, "Error: jfieldID for message context Text is null");
- return nullptr;
- }
- jstring jmsgBody = (jstring)env->GetObjectField( jMsg, fid_body);
- const char *messageBody = "";
- if (jmsgBody)
- {
- messageBody = env->GetStringUTFChars( jmsgBody, NULL);
- }
- else
- {
- NS_LOGD ("Info: messageBody is null");
- }
- NS_LOGD ("Message Body: %s\n", messageBody);
-
- // Message Source
- jfieldID fid_source = env->GetFieldID( cls, "mSourceName", "Ljava/lang/String;");
- if (fid_source == NULL)
- {
- ThrowNSException(JNI_INVALID_VALUE, "Error: jfieldID for message source is null");
- return nullptr;
- }
- jstring jmsgSource = (jstring)env->GetObjectField( jMsg, fid_source);
- const char *messageSource = "";
- if (jmsgSource)
- {
- messageSource = env->GetStringUTFChars( jmsgSource, NULL);
- }
- else
- {
- NS_LOGD ("Info: messageSource is null");
- }
- NS_LOGD ("Message Source: %s\n", messageSource);
-
- // Message Topic
- jfieldID fid_topic = env->GetFieldID( cls, "mTopic", "Ljava/lang/String;");
- if (fid_topic == NULL)
- {
- ThrowNSException(JNI_INVALID_VALUE, "Error: jfieldID for topic is null");
- return nullptr;
- }
- jstring jtopic = (jstring)env->GetObjectField( jMsg, fid_topic);
- const char *topic = "";
- if (jtopic)
- {
- topic = env->GetStringUTFChars( jtopic, NULL);
- }
- else
- {
- NS_LOGD ("Info: topic is null");
- }
- NS_LOGD ("Topic : %s\n", topic);
-
- // Message MediaContents
- jfieldID fid_media = env->GetFieldID( cls, "mMediaContents",
- "Lorg/iotivity/service/ns/common/MediaContents;");
- if (fid_media == NULL)
- {
- ThrowNSException(JNI_INVALID_VALUE, "Error: jfieldID for MediaContents is null");
- return nullptr;
- }
- jobject jmedia = env->GetObjectField( jMsg, fid_media);
- OIC::Service::NSMediaContents *media = nullptr;
- if (jmedia == NULL)
- {
- NS_LOGD ("Info: jmedia object of MediaContents inside Message is null");
- }
- else
- {
- jclass cls_MediaContents = (jclass) (env->NewLocalRef(g_cls_MediaContents));
- if (!cls_MediaContents)
- {
- ThrowNSException(JNI_INVALID_VALUE, "Failed to Get ObjectClass for class MediaContents");
- return nullptr;
- }
- jfieldID fid_icon = env->GetFieldID( cls_MediaContents, "mIconImage", "Ljava/lang/String;");
- if (fid_icon == NULL)
- {
- ThrowNSException(JNI_INVALID_VALUE, "Error: jfieldID for iconImage is null");
- return nullptr;
- }
- jstring jiconImage = (jstring)env->GetObjectField( jmedia, fid_icon);
- const char *iconImage = "";
- if (jiconImage)
- {
- iconImage = env->GetStringUTFChars( jiconImage, NULL);
- media = new OIC::Service::NSMediaContents(std::string(iconImage));
- env->ReleaseStringUTFChars(jiconImage, iconImage);
- }
- else
- {
- NS_LOGD ("Info: iconImage is null");
- }
- env->DeleteLocalRef(cls_MediaContents);
- NS_LOGD ("iconImage: %s\n", iconImage);
- }
-
- // Message ExtraInfo
- jfieldID fid_extraInfo = env->GetFieldID( cls, "mExtraInfo",
- "Lorg/iotivity/base/OcRepresentation;");
- if (fid_extraInfo == NULL)
- {
- ThrowNSException(JNI_INVALID_VALUE, "Error: jfieldID for mExtraInfo is null");
- return nullptr;
- }
- jobject jExtraInfo = env->GetObjectField( jMsg, fid_extraInfo);
- OC::OCRepresentation *representation = nullptr;
- if (jExtraInfo == NULL)
- {
- NS_LOGE ("Error: jExtraInfo object of Message is null");
- }
- else
- {
- representation = GetHandle<OC::OCRepresentation>(env, jExtraInfo);
- if (env->ExceptionCheck())
- {
- NS_LOGE ("Failed to get native handle from OcRepresentation");
- }
- if (!representation)
- {
- NS_LOGE ("Failed to get native object OcRepresentation");
- }
- }
-
- // Message Id
- jfieldID fid_mid = env->GetFieldID( cls, "mMessageId", "J");
- if (fid_mid == NULL)
- {
- ThrowNSException(JNI_INVALID_VALUE, "Error: jfieldID for message mMessageId is null");
- return nullptr;
- }
-
- jlong jId = (jlong) env->GetLongField( jMsg, fid_mid);
- uint64_t jmId = jId;
- NS_LOGD ("Message Id: %lld\n", jmId);
-
- // Provider Id
- jfieldID fid_pid = env->GetFieldID( cls, "mProviderId", "Ljava/lang/String;");
- if (fid_pid == NULL)
- {
- ThrowNSException(JNI_INVALID_VALUE, "Error: jfieldID for message mProviderId is null");
- return nullptr;
- }
- jstring jProId = (jstring)env->GetObjectField( jMsg, fid_pid);
- const char *jpId = "";
- if (jProId)
- {
- jpId = env->GetStringUTFChars( jProId, NULL);
- }
- else
- {
- NS_LOGD ("Info: messageSource is null");
- }
- NS_LOGD ("Provider Id : %s\n", jpId);
-
-
- NSMessage *mesg = new NSMessage;
- mesg->messageId = jmId;
- mesg->providerId[0] = '\0';
- strncat(mesg->providerId, jpId, NS_UTILS_UUID_STRING_SIZE - 1);
-
- mesg->dateTime = nullptr;
- mesg->title = nullptr;
- mesg->contentText = nullptr;
- mesg->sourceName = nullptr;
- mesg->mediaContents = nullptr;
- mesg->topic = nullptr;
- mesg->extraInfo = nullptr;
-
- OIC::Service::NSMessage nsMsg(mesg);
- NS_LOGD ("Created NSMessage");
-
- nsMsg.setType(type);
- nsMsg.setTime(std::string(time));
- nsMsg.setTTL(ttl);
- nsMsg.setTitle(std::string(messageTitle));
- nsMsg.setContentText(std::string(messageBody));
- nsMsg.setSourceName(std::string(messageSource));
- if (media != nullptr)
- {
- nsMsg.setMediaContents(media);
- }
- nsMsg.setTopic(std::string(topic));
- if (representation != nullptr)
- {
- nsMsg.setExtraInfo(*representation);
- }
-
- env->DeleteLocalRef(cls_messageType);
-
- if (jtime)
- {
- env->ReleaseStringUTFChars(jtime, time);
- }
- if (jmsgTitle)
- {
- env->ReleaseStringUTFChars(jmsgTitle, messageTitle);
- }
- if (jmsgBody)
- {
- env->ReleaseStringUTFChars(jmsgBody, messageBody);
- }
- if (jmsgSource)
- {
- env->ReleaseStringUTFChars(jmsgSource, messageSource);
- }
- if (jtopic)
- {
- env->ReleaseStringUTFChars(jtopic, topic);
- }
- delete mesg;
- NS_LOGD ("JNIProviderService: getMessage - OUT");
- return nsMsg;
-
-}
-
-jobject getJavaMessageType(JNIEnv *env, OIC::Service::NSMessage::NSMessageType type)
-{
- NS_LOGD ("JNIProviderService: getJavaMessageType - IN");
- jobject messageType = NULL;
- switch (type)
- {
- case OIC::Service::NSMessage::NSMessageType::NS_MESSAGE_ALERT:
- {
- static jfieldID fieldID = env->GetStaticFieldID(g_cls_Message_Type,
- "ALERT", "Lorg/iotivity/service/ns/common/Message$MessageType;");
- messageType = env->GetStaticObjectField(g_cls_Message_Type, fieldID);
- break;
- }
- case OIC::Service::NSMessage::NSMessageType::NS_MESSAGE_NOTICE:
- {
- static jfieldID fieldID = env->GetStaticFieldID(g_cls_Message_Type,
- "NOTICE", "Lorg/iotivity/service/ns/common/Message$MessageType;");
- messageType = env->GetStaticObjectField(g_cls_Message_Type, fieldID);
- break;
- }
- case OIC::Service::NSMessage::NSMessageType::NS_MESSAGE_EVENT:
- {
- static jfieldID fieldID = env->GetStaticFieldID(g_cls_Message_Type,
- "EVENT", "Lorg/iotivity/service/ns/common/Message$MessageType;");
- messageType = env->GetStaticObjectField(g_cls_Message_Type, fieldID);
- break;
- }
- case OIC::Service::NSMessage::NSMessageType::NS_MESSAGE_INFO:
- {
- static jfieldID fieldID = env->GetStaticFieldID(g_cls_Message_Type,
- "INFO", "Lorg/iotivity/service/ns/common/Message$MessageType;");
- messageType = env->GetStaticObjectField(g_cls_Message_Type, fieldID);
- break;
- }
- default:
- {
- messageType = NULL;
- break;
- }
- }
- NS_LOGD ("JNIProviderService: getJavaMessageType - OUT");
- return messageType;
-}
-
-jobject getJavaMessage(JNIEnv *env, OIC::Service::NSMessage message)
-{
- NS_LOGD ("JNIProviderService: getJavaMessage - IN");
-
- NS_LOGD ("id : %llu\n", message.getMessageId());
- NS_LOGD ("title : %s\n", message.getTitle().c_str());
- NS_LOGD ("content : %s\n", message.getContentText().c_str());
- NS_LOGD ("source : %s\n", message.getSourceName().c_str());
-
- jlong jMessageId = (jlong) message.getMessageId();
- jstring jProviderId = env->NewStringUTF(message.getProviderId().c_str());
- jstring jTitle = env->NewStringUTF(message.getTitle().c_str());
- jstring jContentText = env->NewStringUTF(message.getContentText().c_str());
- jstring jSourceName = env->NewStringUTF(message.getSourceName().c_str());
- jstring jTopic = env->NewStringUTF(message.getTopic().c_str());
-
- jstring jTime = env->NewStringUTF(message.getTime().c_str());
- jlong jTTL = (jlong) message.getTTL();
-
- jclass cls_message = (jclass) (env->NewLocalRef(g_cls_Message));
- if (!cls_message)
- {
- NS_LOGE ("Failed to Get ObjectClass for Message");
- return NULL ;
- }
- jmethodID mid_message = env->GetMethodID(
- cls_message, "<init>",
- "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V");
- if (!mid_message)
- {
- NS_LOGE ("Failed to Get MethodID for Message<init>");
- return NULL;
- }
- jobject obj_message = env->NewObject(cls_message, mid_message,
- jTitle, jContentText, jSourceName);
- if (!obj_message)
- {
- NS_LOGE ("Failed to Get Java Object for Message");
- return NULL;
- }
-
- jfieldID fid_messageId = env->GetFieldID(cls_message, "mMessageId", "J");
- if (!fid_messageId)
- {
- NS_LOGE ("Failed to get field MessageID for Message");
- return NULL;
- }
- env->SetLongField(obj_message, fid_messageId, jMessageId);
-
- jfieldID fid_providerId = env->GetFieldID(cls_message, "mProviderId", "Ljava/lang/String;");
- if (!fid_providerId)
- {
- NS_LOGE ("Failed to get field ProviderID for Message");
- return NULL;
- }
- env->SetObjectField(obj_message, fid_providerId, jProviderId);
-
- jfieldID fid_time = env->GetFieldID(cls_message, "mTime", "Ljava/lang/String;");
- if (!fid_time)
- {
- NS_LOGE ("Failed to get field Time for Message");
- return NULL;
- }
- env->SetObjectField(obj_message, fid_time, jTime);
-
- jfieldID fid_ttl = env->GetFieldID(cls_message, "mTTL", "J");
- if (!fid_ttl)
- {
- NS_LOGE ("Failed to get field TTL for Message");
- return NULL;
- }
- env->SetLongField(obj_message, fid_ttl, jTTL);
-
- jfieldID fid_topic = env->GetFieldID(cls_message, "mTopic", "Ljava/lang/String;");
- if (!fid_topic)
- {
- NS_LOGE ("Failed to get mTopic for Message");
- return NULL;
- }
- env->SetObjectField(obj_message, fid_topic, jTopic);
-
- OIC::Service::NSMediaContents *mediaCont = message.getMediaContents();
- if (mediaCont != nullptr)
- {
- jstring jIconImage = env->NewStringUTF(mediaCont->getIconImage().c_str());
- jclass cls_mediaContents = (jclass) (env->NewLocalRef(g_cls_MediaContents));
- if (!cls_mediaContents)
- {
- NS_LOGE ("Failed to Get ObjectClass for MediaContents");
- return NULL;
- }
- jmethodID mid_mediaContents = env->GetMethodID(
- cls_mediaContents, "<init>", "(Ljava/lang/String;)V");
- if (!mid_mediaContents)
- {
- NS_LOGE ("Failed to Get MethodID for MediaContents<init>");
- return NULL;
- }
- jobject obj_mediaContents = env->NewObject(cls_mediaContents, mid_mediaContents,
- jIconImage);
-
- jfieldID fid_mediaContents = env->GetFieldID(cls_message, "mMediaContents",
- "Lorg/iotivity/service/ns/common/MediaContents;");
- if (!fid_mediaContents)
- {
- NS_LOGE ("Failed to get field mediaContents for Message");
- return NULL;
- }
- env->SetObjectField(obj_message, fid_mediaContents, obj_mediaContents);
-
- }
-
- jobject jType = getJavaMessageType(env, message.getType());
- if (jType)
- {
- jfieldID fid_type = env->GetFieldID(cls_message, "mType",
- "Lorg/iotivity/service/ns/common/Message$MessageType;");
- if (!fid_type)
- {
- NS_LOGE ("Failed to get field Type for Message");
- return NULL;
- }
- env->SetObjectField(obj_message, fid_type, jType);
- }
-
- NS_LOGD ("Reading OCRepresentation Object from Native");
- OC::OCRepresentation *ocRepresentation = new OC::OCRepresentation(message.getExtraInfo());
- jlong handle = reinterpret_cast<jlong>(ocRepresentation);
- jobject jRepresentation = env->NewObject(g_cls_OcRepresentation, g_mid_OcRepresentation_N_ctor_bool,
- handle, true);
- if (!jRepresentation)
- {
- NS_LOGE ("Failed to create OcRepresentation");
- delete ocRepresentation;
- }
- else
- {
- NS_LOGD ("Created OCRepresentation Object from Native");
- }
- jfieldID fid_extraInfo = env->GetFieldID(cls_message, "mExtraInfo",
- "Lorg/iotivity/base/OcRepresentation;");
- if (!fid_extraInfo)
- {
- NS_LOGE ("Failed to get mExtraInfo for Message");
- delete ocRepresentation;
- return NULL;
- }
- NS_LOGD ("setting extraInfo field");
- env->SetObjectField(obj_message, fid_extraInfo, jRepresentation);
-
- env->DeleteLocalRef(cls_message);
- NS_LOGD ("JNIProviderService: getJavaMessage - OUT");
- return obj_message;
-}
-
-jobject getJavaTopicState(JNIEnv *env, OIC::Service::NSTopic::NSTopicState nsState)
-{
- NS_LOGD ("JNIProviderService: getJavaTopicState - IN");
-
- // TopicState
- jclass cls_topicState = (jclass) (env->NewLocalRef(g_cls_TopicState));
- if (!cls_topicState)
- {
- NS_LOGE ("Failed to Get ObjectClass for TopicState Type");
- return NULL;
- }
- jobject topicState = NULL;
-
- switch (nsState)
- {
- case OIC::Service::NSTopic::NSTopicState::UNSUBSCRIBED:
- {
- static jfieldID fieldID = env->GetStaticFieldID(cls_topicState,
- "UNSUBSCRIBED", "Lorg/iotivity/service/ns/common/Topic$TopicState;");
- topicState = env->GetStaticObjectField(cls_topicState, fieldID);
- break;
- }
- case OIC::Service::NSTopic::NSTopicState::SUBSCRIBED:
- {
- static jfieldID fieldID = env->GetStaticFieldID(cls_topicState,
- "SUBSCRIBED", "Lorg/iotivity/service/ns/common/Topic$TopicState;");
- topicState = env->GetStaticObjectField(cls_topicState, fieldID);
- break;
- }
- default:
- {
- topicState = NULL;
- break;
- }
- }
-
- NS_LOGD ("JNIProviderService: getJavaTopicState - OUT");
- return topicState;
-}
-
-jobject getJavaTopicsList(JNIEnv *env, std::shared_ptr<OIC::Service::NSTopicsList> topicList)
-{
- NS_LOGD ("JNIProviderService: getJavaTopicsList - IN");
- jclass cls_topicList = (jclass) (env->NewLocalRef(g_cls_TopicsList));
- if (!cls_topicList)
- {
- NS_LOGE ("Failed to Get ObjectClass for TopicsList");
- return NULL;
- }
- jmethodID mid_topicList = env->GetMethodID(cls_topicList, "<init>", "()V");
- if (!mid_topicList)
- {
- NS_LOGE ("Failed to Get MethodID for TopicsList<init>");
- return NULL;
- }
- jobject obj_topicList = env->NewObject(cls_topicList, mid_topicList);
- if (!obj_topicList)
- {
- NS_LOGE ("Failed to Get object for TopicsList");
- return NULL;
- }
- jmethodID mid_addTopic = env->GetMethodID(cls_topicList, "addTopic",
- "(Ljava/lang/String;Lorg/iotivity/service/ns/common/Topic$TopicState;)V");
- if (!mid_addTopic)
- {
- NS_LOGE ("Failed to Get MethodID for addTopic");
- return NULL;
- }
- for (auto it : topicList->getTopicsList())
- {
- jobject jState = getJavaTopicState(env, it.getState());
- std::string topicName = it.getTopicName();
- jstring jTopicName = env->NewStringUTF(topicName.c_str());
- env->CallVoidMethod(obj_topicList, mid_addTopic, jTopicName, jState);
- }
- env->DeleteLocalRef(cls_topicList);
- NS_LOGD ("JNIProviderService: getJavaTopicsList - OUT");
- return obj_topicList;
-}
-
-jobject getJavaSyncType(JNIEnv *env, OIC::Service::NSSyncInfo::NSSyncType nsType)
-{
- NS_LOGD ("JNIProviderService: getJavaSyncType - IN");
-
- // SyncType
- jclass cls_SyncType = (jclass) (env->NewLocalRef(g_cls_SyncType));
- if (!cls_SyncType)
- {
- NS_LOGE ("Failed to Get ObjectClass for SyncType");
- return NULL;
- }
- jobject syncType = NULL;
- switch (nsType)
- {
- case OIC::Service::NSSyncInfo::NSSyncType::NS_SYNC_UNREAD:
- {
- static jfieldID fieldID = env->GetStaticFieldID(cls_SyncType,
- "UNREAD", "Lorg/iotivity/service/ns/common/SyncInfo$SyncType;");
- syncType = env->GetStaticObjectField(cls_SyncType, fieldID);
- break;
- }
- case OIC::Service::NSSyncInfo::NSSyncType::NS_SYNC_READ :
- {
- static jfieldID fieldID = env->GetStaticFieldID(cls_SyncType,
- "READ", "Lorg/iotivity/service/ns/common/SyncInfo$SyncType;");
- syncType = env->GetStaticObjectField(cls_SyncType, fieldID);
- break;
- }
- case OIC::Service::NSSyncInfo::NSSyncType::NS_SYNC_DELETED :
- {
- static jfieldID fieldID = env->GetStaticFieldID(cls_SyncType,
- "DELETED", "Lorg/iotivity/service/ns/common/SyncInfo$SyncType;");
- syncType = env->GetStaticObjectField(cls_SyncType, fieldID);
- break;
- }
- default:
- {
- syncType = NULL;
- break;
- }
- }
-
- NS_LOGD ("JNIProviderService: getJavaSyncType - OUT");
- return syncType;
-}
-
-
-void onSubscribeListenerCb(std::shared_ptr<OIC::Service::NSConsumer> consumer)
-{
- NS_LOGD ("JNIProviderService_onSubscribeListenerCb - IN");
-
- jint envRet = 0;;
- JNIEnv *env = GetJNIEnv(&envRet);
- if (NULL == env)
- {
- return ;
- }
-
- jobject jSubscriptionListener = (jobject) env->NewLocalRef(g_obj_subscriptionListener);
- if (!jSubscriptionListener)
- {
- NS_LOGE ("Failed to Get jSubscriptionListener");
- if (JNI_EDETACHED == envRet)
- {
- g_jvm_provider->DetachCurrentThread();
- }
- return ;
- }
-
- NS_LOGD ("consumer ID : %s\n", consumer->getConsumerId().c_str());
-
- jstring jConsumerId = env->NewStringUTF( consumer->getConsumerId().c_str());
-
- jclass cls_consumer = (jclass) (env->NewLocalRef(g_cls_Consumer));
- if (!cls_consumer)
- {
- NS_LOGE ("Failed to Get ObjectClass for Consumer");
- if (JNI_EDETACHED == envRet)
- {
- g_jvm_provider->DetachCurrentThread();
- }
- return ;
- }
-
- jmethodID mid_consumer = env->GetMethodID(
- cls_consumer,
- "<init>",
- "(Ljava/lang/String;)V");
- if (!mid_consumer)
- {
- NS_LOGE ("Failed to Get MethodID for Consumer<init>");
- if (JNI_EDETACHED == envRet)
- {
- g_jvm_provider->DetachCurrentThread();
- }
- return ;
- }
- jobject obj_consumer = env->NewObject( cls_consumer, mid_consumer, jConsumerId);
-
- jclass cls = env->GetObjectClass( jSubscriptionListener);
- if (!cls)
- {
- NS_LOGE ("Failed to Get ObjectClass of jSubscriptionListener");
- if (JNI_EDETACHED == envRet)
- {
- g_jvm_provider->DetachCurrentThread();
- }
- return;
- }
- jmethodID mid = env->GetMethodID(
- cls,
- "onConsumerSubscribed",
- "(Lorg/iotivity/service/ns/provider/Consumer;)V");
- if (!mid)
- {
- NS_LOGE ("Failed to Get MethodID of onConsumerSubscribed");
- if (JNI_EDETACHED == envRet)
- {
- g_jvm_provider->DetachCurrentThread();
- }
- return;
- }
-
- env->CallVoidMethod( jSubscriptionListener, mid, obj_consumer);
- env->DeleteLocalRef(jSubscriptionListener);
- env->DeleteLocalRef(cls_consumer);
- if (JNI_EDETACHED == envRet)
- {
- g_jvm_provider->DetachCurrentThread();
- }
- NS_LOGD ("JNIProviderService_onSubscribeListenerCb - OUT");
- return;
-}
-
-void onSyncInfoListenerCb(OIC::Service::NSSyncInfo sync)
-{
- NS_LOGD ("JNIProviderService_onSyncInfoListenerCb - IN");
-
- jint envRet = 0;;
- JNIEnv *env = GetJNIEnv(&envRet);
- if (NULL == env)
- {
- return ;
- }
-
- jobject jSyncListener = (jobject) env->NewLocalRef(g_obj_syncListener);
- if (!jSyncListener)
- {
- NS_LOGE ("Failed to Get jSyncListener");
- if (JNI_EDETACHED == envRet)
- {
- g_jvm_provider->DetachCurrentThread();
- }
- return ;
- }
-
- NS_LOGD ("Sync ID : %ld\n", (long) sync.getMessageId());
- NS_LOGD ("Sync STATE : %d\n", (int) sync.getState());
-
- jlong jMessageId = (long) sync.getMessageId();
- jstring jProviderId = env->NewStringUTF(sync.getProviderId().c_str());
- jobject syncType = getJavaSyncType(env, sync.getState());
- if (!syncType)
- {
- NS_LOGE ("Failed to Get syncType for SyncInfo");
- if (JNI_EDETACHED == envRet)
- {
- g_jvm_provider->DetachCurrentThread();
- }
- return ;
- }
- jclass cls_SyncInfo = (jclass) (env->NewLocalRef(g_cls_SyncInfo));
- if (!cls_SyncInfo)
- {
- NS_LOGE ("Failed to Get ObjectClass for SyncInfo");
- if (JNI_EDETACHED == envRet)
- {
- g_jvm_provider->DetachCurrentThread();
- }
- return ;
- }
- jmethodID mid_syncInfo = env->GetMethodID(
- cls_SyncInfo,
- "<init>",
- "(JLjava/lang/String;Lorg/iotivity/service/ns/common/SyncInfo$SyncType;)V");
- if (!mid_syncInfo)
- {
- NS_LOGE ("Failed to Get MethodID for SyncInfo");
- if (JNI_EDETACHED == envRet)
- {
- g_jvm_provider->DetachCurrentThread();
- }
- return ;
- }
-
- jobject obj_syncInfo = env->NewObject( cls_SyncInfo, mid_syncInfo,
- jMessageId, jProviderId, syncType);
- if (!obj_syncInfo)
- {
- NS_LOGE ("Failed to Get Object for SyncInfo");
- if (JNI_EDETACHED == envRet)
- {
- g_jvm_provider->DetachCurrentThread();
- }
- return ;
- }
-
- jclass cls = env->GetObjectClass( jSyncListener);
- if (!cls)
- {
- NS_LOGE ("Failed to Get ObjectClass");
- if (JNI_EDETACHED == envRet)
- {
- g_jvm_provider->DetachCurrentThread();
- }
- return ;
- }
- jmethodID mid = env->GetMethodID(
- cls,
- "onMessageSynchronized",
- "(Lorg/iotivity/service/ns/common/SyncInfo;)V");
- if (!mid)
- {
- NS_LOGE ("Failed to Get MethodID");
- if (JNI_EDETACHED == envRet)
- {
- g_jvm_provider->DetachCurrentThread();
- }
- return ;
- }
- env->CallVoidMethod( jSyncListener, mid, obj_syncInfo);
-
- env->DeleteLocalRef(jSyncListener);
- env->DeleteLocalRef(cls_SyncInfo);
- if (JNI_EDETACHED == envRet)
- {
- g_jvm_provider->DetachCurrentThread();
- }
- NS_LOGD ("JNIProviderService: OnSyncInfoListenerCb - OUT");
- return;
-
-}
-
-JNIEXPORT void JNICALL Java_org_iotivity_service_ns_provider_ProviderService_nativeStart
-(JNIEnv *env, jobject jObj, jobject jSubscriptionListener, jobject jSyncListener,
- jboolean jPolicy, jstring jUserInfo, jboolean jResourceSecurity)
-{
- NS_LOGD ("JNIProviderService: nativeStart - IN");
- if (!jSubscriptionListener || !jSyncListener)
- {
- ThrowNSException(JNI_INVALID_VALUE, "Listener cannot be null");
- return;
- }
-
- if (g_obj_subscriptionListener != NULL)
- {
- env->DeleteGlobalRef(g_obj_subscriptionListener);
- }
- if (g_obj_syncListener != NULL)
- {
- env->DeleteGlobalRef(g_obj_syncListener);
- }
-
- g_obj_subscriptionListener = (jobject) env->NewGlobalRef(jSubscriptionListener);
- g_obj_syncListener = (jobject) env->NewGlobalRef(jSyncListener);
-
- // check access policy
-
- OIC::Service::NSProviderService::ProviderConfig cfg;
- cfg.m_subscribeRequestCb = onSubscribeListenerCb;
- cfg.m_syncInfoCb = onSyncInfoListenerCb;
- cfg.subControllability = (bool) jPolicy;
- if (!jUserInfo)
- {
- const char *info = env->GetStringUTFChars( jUserInfo, NULL);
- std::string userInfo(info);
- cfg.userInfo = userInfo;
- }
- cfg.resourceSecurity = (bool) jResourceSecurity;
-
- OIC::Service::NSResult result = OIC::Service::NSProviderService::getInstance()->start(cfg);
- if (result != OIC::Service::NSResult::OK)
- {
- ThrowNSException((int) result, "Fail to start NSProviderService");
- return;
- }
-
- NS_LOGD ("JNIProviderService: nativeStart - OUT");
- return;
-}
-
-JNIEXPORT void JNICALL Java_org_iotivity_service_ns_provider_ProviderService_nativeStop
-(JNIEnv *env, jobject jObj)
-{
- NS_LOGD ("JNIProviderService: nativeStop - IN");
-
- OIC::Service::NSResult result = OIC::Service::NSProviderService::getInstance()->stop();
- if (result != OIC::Service::NSResult::OK)
- {
- ThrowNSException((int) result, "Fail to stop NSProviderService");
- return;
- }
-
- env->DeleteGlobalRef( g_obj_subscriptionListener);
- env->DeleteGlobalRef( g_obj_syncListener);
- g_obj_subscriptionListener = NULL;
- g_obj_syncListener = NULL;
-
- NS_LOGD ("JNIProviderService: nativeStop - OUT");
- return;
-}
-
-JNIEXPORT void JNICALL Java_org_iotivity_service_ns_provider_ProviderService_nativeSendMessage
-(JNIEnv *env, jobject jObj, jobject jMsg)
-{
- NS_LOGD ("JNIProviderService: nativeSendMessage - IN");
- if (!jMsg)
- {
- ThrowNSException(JNI_INVALID_VALUE, "Message cannot be null");
- return;
- }
- OIC::Service::NSMessage nsMsg = getNativeMessage(env, jMsg);
-
- OIC::Service::NSResult result = OIC::Service::NSProviderService::getInstance()->sendMessage(nsMsg);
- if (result != OIC::Service::NSResult::OK)
- {
- ThrowNSException((int) result, "Fail to send NSProvider Message");
- return;
- }
- NS_LOGD ("JNIProviderService: nativeSendMessage - OUT");
- return;
-}
-
-JNIEXPORT void JNICALL Java_org_iotivity_service_ns_provider_ProviderService_nativeSendSyncInfo
-(JNIEnv *env, jobject jObj, jlong messageId , jint syncState)
-{
- NS_LOGD ("JNIProviderService: nativeSendSyncInfo - IN");
- OIC::Service::NSResult result = OIC::Service::NSProviderService::getInstance()->sendSyncInfo(
- messageId,
- (OIC::Service::NSSyncInfo::NSSyncType) syncState);
- if (result != OIC::Service::NSResult::OK)
- {
- ThrowNSException((int) result, "Fail to send NSProvider SendSyncInfo");
- return;
- }
- NS_LOGD ("JNIProviderService: nativeSendSyncInfo - OUT");
- return;
-}
-
-JNIEXPORT jobject JNICALL Java_org_iotivity_service_ns_provider_ProviderService_nativeCreateMessage
-(JNIEnv *env, jobject jObj)
-{
- NS_LOGD ("JNIProviderService: nativeCreateMessage - IN");
- OIC::Service::NSMessage message =
- OIC::Service::NSProviderService::getInstance()->createMessage();
- jobject jMsg = getJavaMessage(env, message);
- if (!jMsg)
- {
- ThrowNSException(JNI_INVALID_VALUE, "Couldn't create Java Message");
- return NULL;
- }
- NS_LOGD ("JNIProviderService: nativeCreateMessage - OUT");
- return jMsg;
-}
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_ns_provider_ProviderService_nativeEnableRemoteService
-(JNIEnv *env, jobject jObj, jstring jstr)
-{
- NS_LOGD ("JNIProviderService: nativeEnableRemoteService - IN");
- if (!jstr)
- {
- ThrowNSException(JNI_INVALID_VALUE, "Server Address Can't be NULL");
- return;
- }
-
- const char *address = env->GetStringUTFChars( jstr, NULL);
- std::string servAddress(address);
- OIC::Service::NSResult result =
- OIC::Service::NSProviderService::getInstance()->enableRemoteService(
- servAddress);
- if (result != OIC::Service::NSResult::OK)
- {
- ThrowNSException((int) result, "Fail to Enable Remote Service");
- return;
- }
- env->ReleaseStringUTFChars(jstr, address);
- NS_LOGD ("JNIProviderService: nativeEnableRemoteService - OUT");
- return;
-}
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_ns_provider_ProviderService_nativeDisableRemoteService
-(JNIEnv *env, jobject jObj, jstring jstr)
-{
- NS_LOGD ("JNIProviderService: nativeDisableRemoteService - IN");
- if (!jstr)
- {
- ThrowNSException(JNI_INVALID_VALUE, "Server Address Can't be NULL");
- return;
- }
-
- const char *address = env->GetStringUTFChars( jstr, NULL);
- std::string servAddress(address);
- OIC::Service::NSResult result =
- OIC::Service::NSProviderService::getInstance()->disableRemoteService(
- servAddress);
- if (result != OIC::Service::NSResult::OK)
- {
- ThrowNSException((int) result, "Fail to Disable Remote Service");
- return;
- }
- env->ReleaseStringUTFChars(jstr, address);
- NS_LOGD ("JNIProviderService: nativeDisableRemoteService - OUT");
- return;
-}
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_ns_provider_ProviderService_nativeSubscribeMQService
-(JNIEnv *env, jobject jObj, jstring jserverAddress, jstring jTopicName)
-{
- NS_LOGD ("JNIProviderService: nativeSubscribeMQService - IN");
- if (!jserverAddress)
- {
- ThrowNSException(JNI_INVALID_VALUE, "Server Address Can't be NULL");
- return;
- }
- if (!jTopicName)
- {
- ThrowNSException(JNI_INVALID_VALUE, "TopicName Can't be NULL");
- return;
- }
-
- const char *address = env->GetStringUTFChars( jserverAddress, NULL);
- std::string servAddress(address);
- const char *topic = env->GetStringUTFChars( jTopicName, NULL);
- std::string topicName(topic);
-
- OIC::Service::NSResult result =
- OIC::Service::NSProviderService::getInstance()->subscribeMQService(
- servAddress, topicName);
- if (result != OIC::Service::NSResult::OK)
- {
- ThrowNSException((int) result, "Fail to Subscribe to MQ Service");
- return;
- }
- env->ReleaseStringUTFChars(jserverAddress, address);
- env->ReleaseStringUTFChars(jTopicName, topic);
- NS_LOGD ("JNIProviderService: nativeSubscribeMQService - OUT");
- return;
-}
-
-JNIEXPORT void JNICALL Java_org_iotivity_service_ns_provider_ProviderService_nativeRegisterTopic
-(JNIEnv *env, jobject jObj, jstring jTopicName)
-{
- NS_LOGD ("JNIProviderService: nativeRegisterTopic - IN");
- if (!jTopicName)
- {
- ThrowNSException(JNI_INVALID_VALUE, "Topic Name Can't be NULL");
- return;
- }
- const char *name = env->GetStringUTFChars( jTopicName, NULL);
- std::string topicName(name);
- OIC::Service::NSResult result = OIC::Service::NSProviderService::getInstance()->registerTopic(
- topicName);
- if (result != OIC::Service::NSResult::OK)
- {
- ThrowNSException((int) result, "Fail to Register Topic");
- return;
- }
- env->ReleaseStringUTFChars(jTopicName, name);
- NS_LOGD ("JNIProviderService: nativeRegisterTopic - OUT");
- return;
-}
-JNIEXPORT void JNICALL Java_org_iotivity_service_ns_provider_ProviderService_nativeUnregisterTopic
-(JNIEnv *env, jobject jObj, jstring jTopicName)
-{
- NS_LOGD ("JNIProviderService: nativeUnregisterTopic - IN");
- if (!jTopicName)
- {
- ThrowNSException(JNI_INVALID_VALUE, "Topic Name Can't be NULL");
- return;
- }
- const char *name = env->GetStringUTFChars( jTopicName, NULL);
- std::string topicName(name);
- OIC::Service::NSResult result = OIC::Service::NSProviderService::getInstance()->unregisterTopic(
- topicName);
- if (result != OIC::Service::NSResult::OK)
- {
- ThrowNSException((int) result, "Fail to Unregister Topic");
- return;
- }
- env->ReleaseStringUTFChars(jTopicName, name);
- NS_LOGD ("JNIProviderService: nativeUnregisterTopic - OUT");
- return;
-}
-
-JNIEXPORT jobject JNICALL
-Java_org_iotivity_service_ns_provider_ProviderService_nativeGetRegisteredTopicList
-(JNIEnv *env, jobject jObj)
-{
- NS_LOGD ("JNIProviderService: nativeGetRegisteredTopicList - IN");
-
- std::shared_ptr<OIC::Service::NSTopicsList> topicList =
- OIC::Service::NSProviderService::getInstance()->getRegisteredTopicList();
- if (topicList == nullptr)
- {
- ThrowNSException(JNI_INVALID_VALUE, "Topic List doesn't exist");
- return NULL;
- }
-
- jobject obj_topicList = getJavaTopicsList(env, topicList);
-
- NS_LOGD ("JNIProviderService: nativeGetRegisteredTopicList - OUT");
- return obj_topicList;
-}
-
-JNIEXPORT void JNICALL Java_org_iotivity_service_ns_provider_Consumer_nativeAcceptSubscription
-(JNIEnv *env, jobject jObj, jstring jConsumerId, jboolean jAccepted)
-{
- NS_LOGD ("JNIProviderService: nativeAcceptSubscription - IN");
- if (!jConsumerId)
- {
- ThrowNSException(JNI_INVALID_VALUE, "ConsumerId Can't be NULL");
- return;
- }
- const char *id = env->GetStringUTFChars( jConsumerId, NULL);
- std::string consumerId(id);
- NS_LOGD ("Consumer ID: %s\n", consumerId.c_str());
-
- std::shared_ptr<OIC::Service::NSConsumer> consumer =
- OIC::Service::NSProviderService::getInstance()->getConsumer(consumerId);
- if (consumer)
- {
- OIC::Service::NSResult result = OIC::Service::NSResult::ERROR;
- try
- {
- result = consumer->acceptSubscription((bool)jAccepted);
- }
- catch (OIC::Service::NSException ex)
- {
- ThrowNSException(NATIVE_EXCEPTION, ex.what());
- return;
- }
- if (result != OIC::Service::NSResult::OK)
- {
- ThrowNSException((int) result, "Fail to acceptSubscription");
- return;
- }
- }
- else
- {
- NS_LOGE ("Couldn't find consumer");
- ThrowNSException(JNI_NO_NATIVE_POINTER, "Fail to find native consumer");
- }
- return;
-}
-JNIEXPORT void JNICALL Java_org_iotivity_service_ns_provider_Consumer_nativeSetConsumerTopic
-(JNIEnv *env, jobject jObj, jstring jConsumerId, jstring jTopicName)
-{
- NS_LOGD ("JNIProviderService: nativeSetConsumerTopic - IN");
- if (!jConsumerId || !jTopicName)
- {
- ThrowNSException(JNI_INVALID_VALUE, "Topic Name or ConsumerId Can't be NULL");
- return;
- }
- const char *name = env->GetStringUTFChars( jTopicName, NULL);
- const char *id = env->GetStringUTFChars( jConsumerId, NULL);
- std::string topicName(name);
- std::string consumerId(id);
- std::shared_ptr<OIC::Service::NSConsumer> nsConsumer =
- OIC::Service::NSProviderService::getInstance()->getConsumer(consumerId);
- if (!nsConsumer)
- {
- ThrowNSException(JNI_NO_NATIVE_POINTER, "Consumer does exists");
- return;
- }
- OIC::Service::NSResult result = OIC::Service::NSResult::ERROR;
- try
- {
- result = nsConsumer->setTopic(topicName);
- }
- catch (OIC::Service::NSException ex)
- {
- ThrowNSException(NATIVE_EXCEPTION, ex.what());
- return;
- }
-
- if (result != OIC::Service::NSResult::OK)
- {
- ThrowNSException((int) result, "Fail to Select Topic");
- return;
- }
- env->ReleaseStringUTFChars(jTopicName, name);
- env->ReleaseStringUTFChars(jConsumerId, id);
- NS_LOGD ("JNIProviderService: nativeSetConsumerTopic - OUT");
- return;
-}
-JNIEXPORT void JNICALL Java_org_iotivity_service_ns_provider_Consumer_nativeUnsetConsumerTopic
-(JNIEnv *env, jobject jObj, jstring jConsumerId, jstring jTopicName)
-{
- NS_LOGD ("JNIProviderService: nativeUnsetConsumerTopic - IN");
- if (!jConsumerId || !jTopicName)
- {
- ThrowNSException(JNI_INVALID_VALUE, "Topic Name or ConsumerId Can't be NULL");
- return;
- }
- const char *name = env->GetStringUTFChars( jTopicName, NULL);
- const char *id = env->GetStringUTFChars( jConsumerId, NULL);
- std::string topicName(name);
- std::string consumerId(id);
- std::shared_ptr<OIC::Service::NSConsumer> nsConsumer =
- OIC::Service::NSProviderService::getInstance()->getConsumer(consumerId);
- if (!nsConsumer)
- {
- ThrowNSException(JNI_NO_NATIVE_POINTER, "Consumer does exists");
- return;
- }
- OIC::Service::NSResult result = OIC::Service::NSResult::ERROR;
- try
- {
- result = nsConsumer->unsetTopic(topicName);
- }
- catch (OIC::Service::NSException ex)
- {
- ThrowNSException(NATIVE_EXCEPTION, ex.what());
- return;
- }
-
- if (result != OIC::Service::NSResult::OK)
- {
- ThrowNSException((int) result, "Fail to Unselect Topic");
- return;
- }
- env->ReleaseStringUTFChars(jTopicName, name);
- env->ReleaseStringUTFChars(jConsumerId, id);
- NS_LOGD ("JNIProviderService: nativeUnsetConsumerTopic - OUT");
- return;
-}
-
-JNIEXPORT jobject JNICALL Java_org_iotivity_service_ns_provider_Consumer_nativeGetConsumerTopicList
-(JNIEnv *env, jobject jObj, jstring jConsumerId)
-{
- NS_LOGD ("JNIProviderService: nativeGetConsumerTopicList - IN");
- if (!jConsumerId)
- {
- ThrowNSException(JNI_INVALID_VALUE, "Topic Name or ConsumerId Can't be NULL");
- return NULL;
- }
- const char *id = env->GetStringUTFChars( jConsumerId, NULL);
- std::string consumerId(id);
- std::shared_ptr<OIC::Service::NSConsumer> nsConsumer =
- OIC::Service::NSProviderService::getInstance()->getConsumer(consumerId);
- if (!nsConsumer)
- {
- ThrowNSException(JNI_NO_NATIVE_POINTER, "Consumer does exists");
- return NULL;
- }
- env->ReleaseStringUTFChars(jConsumerId, id);
- std::shared_ptr<OIC::Service::NSTopicsList> topicList = nullptr;
- try
- {
- topicList = nsConsumer->getConsumerTopicList();
- }
- catch (OIC::Service::NSException ex)
- {
- ThrowNSException(NATIVE_EXCEPTION, ex.what());
- return NULL;
- }
- if (topicList == nullptr)
- {
- ThrowNSException(JNI_NO_NATIVE_POINTER, "Topic List doesn't exist");
- return NULL;
- }
- jobject obj_topicList = getJavaTopicsList(env, topicList);
-
- NS_LOGD ("JNIProviderService: nativeGetConsumerTopicList - OUT");
- return obj_topicList;
-}
-
-// JNI OnLoad
-JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *jvm, void *reserved)
-{
- NS_LOGD ("ProviderService_JNI_OnLoad");
- g_jvm_provider = jvm;
-
- JNIEnv *env = NULL;
- if (jvm->GetEnv((void **)&env, JNI_CURRENT_VERSION) != JNI_OK)
- {
- NS_LOGE ("Failed to get the environment using GetEnv()");
- return JNI_ERR;
- }
-
- jclass localMessage = env->FindClass(
- "org/iotivity/service/ns/common/Message");
- if (!localMessage)
- {
- NS_LOGE ("Failed to get local Message class");
- return JNI_ERR;
- }
- g_cls_Message = (jclass) (env->NewGlobalRef(localMessage));
- if (!g_cls_Message)
- {
- NS_LOGE ("Failed to set Global Message reference");
- return JNI_ERR;
- }
-
- jclass localMessageType = env->FindClass(
- "org/iotivity/service/ns/common/Message$MessageType");
- if (!localMessageType)
- {
- NS_LOGE ("Failed to get local Message Type class");
- return JNI_ERR;
- }
- g_cls_Message_Type = (jclass) (env->NewGlobalRef(localMessageType));
- if (!g_cls_Message_Type)
- {
- NS_LOGE ("Failed to set Global Message Type reference");
- return JNI_ERR;
- }
-
- jclass localConsumer = env->FindClass(
- "org/iotivity/service/ns/provider/Consumer");
- if (!localConsumer)
- {
- NS_LOGE ("Failed to get local Provider class");
- return JNI_ERR;
- }
- g_cls_Consumer = (jclass) (env->NewGlobalRef(localConsumer));
- if (!g_cls_Consumer)
- {
- NS_LOGE ("Failed to set Global Provider reference");
- return JNI_ERR;
- }
-
- jclass localSyncInfo = env->FindClass(
- "org/iotivity/service/ns/common/SyncInfo");
- if (!localSyncInfo)
- {
- NS_LOGE ("Failed to get local SyncInfo class");
- return JNI_ERR;
- }
- g_cls_SyncInfo = (jclass) (env->NewGlobalRef(localSyncInfo));
- if (!g_cls_SyncInfo)
- {
- NS_LOGE ("Failed to set Global SyncInfo reference");
- return JNI_ERR;
- }
-
- jclass localSyncType = env->FindClass(
- "org/iotivity/service/ns/common/SyncInfo$SyncType");
- if (!localSyncType)
- {
- NS_LOGE ("Failed to get local SyncType enum");
- return JNI_ERR;
- }
- g_cls_SyncType = (jclass) (env->NewGlobalRef(localSyncType));
- if (!g_cls_SyncType)
- {
- NS_LOGE ("Failed to set Global SyncType reference");
- return JNI_ERR;
- }
-
- jclass localMediaContents = env->FindClass(
- "org/iotivity/service/ns/common/MediaContents");
- if (!localMediaContents)
- {
- NS_LOGE ("Failed to get local MediaContents class");
- return JNI_ERR;
- }
- g_cls_MediaContents = (jclass) (env->NewGlobalRef(localMediaContents));
- if (!g_cls_MediaContents)
- {
- NS_LOGE ("Failed to set Global MediaContents reference");
- return JNI_ERR;
- }
-
- jclass localTopic = env->FindClass(
- "org/iotivity/service/ns/common/Topic");
- if (!localTopic)
- {
- NS_LOGE ("Failed to get local Topic class");
- return JNI_ERR;
- }
- g_cls_Topic = (jclass) (env->NewGlobalRef(localTopic));
- if (!g_cls_Topic)
- {
- NS_LOGE ("Failed to set Global Topic reference");
- return JNI_ERR;
- }
-
- jclass localTopicsList = env->FindClass(
- "org/iotivity/service/ns/common/TopicsList");
- if (!localTopicsList)
- {
- NS_LOGE ("Failed to get local Topic class");
- return JNI_ERR;
- }
- g_cls_TopicsList = (jclass) (env->NewGlobalRef(localTopicsList));
- if (!g_cls_TopicsList)
- {
- NS_LOGE ("Failed to set Global TopicsList reference");
- return JNI_ERR;
- }
-
- jclass localTopicState = env->FindClass(
- "org/iotivity/service/ns/common/Topic$TopicState");
- if (!localTopicState)
- {
- NS_LOGE ("Failed to get local TopicState enum");
- return JNI_ERR;
- }
- g_cls_TopicState = (jclass) (env->NewGlobalRef(localTopicState));
- if (!g_cls_TopicState)
- {
- NS_LOGE ("Failed to set Global TopicState reference");
- return JNI_ERR;
- }
-
- //OcRepresentation
- jclass localOcRepresentation = env->FindClass("org/iotivity/base/OcRepresentation");
- if (!localOcRepresentation)
- {
- NS_LOGE ("Failed to get local OcRepresentation class");
- return JNI_ERR;
- }
- g_cls_OcRepresentation = (jclass) env->NewGlobalRef(localOcRepresentation);
- if (!g_cls_OcRepresentation)
- {
- NS_LOGE ("Failed to set Global OcRepresentation reference");
- return JNI_ERR;
- }
-
- g_mid_OcRepresentation_N_ctor_bool = env->GetMethodID(g_cls_OcRepresentation, "<init>", "(JZ)V");
- if (!g_mid_OcRepresentation_N_ctor_bool)
- {
- NS_LOGE ("Failed to get Global OcRepresentation Constructor reference");
- return JNI_ERR;
- }
-
- env->DeleteLocalRef(localMessage);
- env->DeleteLocalRef(localMessageType);
- env->DeleteLocalRef(localConsumer);
- env->DeleteLocalRef(localSyncInfo);
- env->DeleteLocalRef(localSyncType);
- env->DeleteLocalRef(localMediaContents);
- env->DeleteLocalRef(localTopic);
- env->DeleteLocalRef(localTopicsList);
- env->DeleteLocalRef(localTopicState);
- env->DeleteLocalRef(localOcRepresentation);
-
- return NSExceptionInit(env);
-}
-
-JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *jvm, void *reserved)
-{
- NS_LOGD ("ProviderService_JNI_OnUnload");
- JNIEnv *env = NULL;
-
- if (jvm->GetEnv((void **)&env, JNI_CURRENT_VERSION) != JNI_OK)
- {
- NS_LOGE ("Failed to get the environment using GetEnv()");
- return ;
- }
-
- env->DeleteGlobalRef(g_cls_Message);
- env->DeleteGlobalRef(g_cls_Consumer);
- env->DeleteGlobalRef(g_cls_SyncInfo);
- env->DeleteGlobalRef(g_cls_SyncType);
- env->DeleteGlobalRef(g_cls_MediaContents);
- env->DeleteGlobalRef(g_cls_Message_Type);
- env->DeleteGlobalRef(g_cls_Topic);
- env->DeleteGlobalRef(g_cls_TopicsList);
- env->DeleteGlobalRef(g_cls_TopicState);
- env->DeleteGlobalRef(g_cls_OcRepresentation);
-}
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2016 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 "JniNotificationCommon.h"
-
-#ifndef JNI_NOTIFICATION_PROVIDER_H
-#define JNI_NOTIFICATION_PROVIDER_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/*
- * Class: org_iotivity_service_ns_provider_ProviderService
- * Method: nativeStart
- * Signature: (Lorg/iotivity/service/ns/provider/ProviderService/OnConsumerSubscribedListener;Lorg/iotivity/service/ns/provider/ProviderService/OnMessageSynchronizedListener;ZLjava/lang/String;Z)V
- */
-JNIEXPORT void JNICALL Java_org_iotivity_service_ns_provider_ProviderService_nativeStart
-(JNIEnv *, jobject, jobject, jobject, jboolean, jstring, jboolean);
-
-/*
- * Class: org_iotivity_service_ns_provider_ProviderService
- * Method: nativeStop
- * Signature: ()V
- */
-JNIEXPORT void JNICALL Java_org_iotivity_service_ns_provider_ProviderService_nativeStop
-(JNIEnv *, jobject);
-
-/*
- * Class: org_iotivity_service_ns_provider_ProviderService
- * Method: nativeSendMessage
- * Signature: (Lorg/iotivity/service/ns/common/Message;)V
- */
-JNIEXPORT void JNICALL Java_org_iotivity_service_ns_provider_ProviderService_nativeSendMessage
-(JNIEnv *, jobject, jobject);
-
-/*
- * Class: org_iotivity_service_ns_provider_ProviderService
- * Method: nativeSendSyncInfo
- * Signature: (JI)V
- */
-JNIEXPORT void JNICALL Java_org_iotivity_service_ns_provider_ProviderService_nativeSendSyncInfo
-(JNIEnv *, jobject, jlong, jint);
-
-/*
- * Class: org_iotivity_service_ns_provider_ProviderService
- * Method: nativeCreateMessage
- * Signature: ()Lorg/iotivity/service/ns/common/Message;
- */
-JNIEXPORT jobject JNICALL Java_org_iotivity_service_ns_provider_ProviderService_nativeCreateMessage
-(JNIEnv *, jobject);
-
-/*
- * Class: org_iotivity_service_ns_provider_ProviderService
- * Method: nativeEnableRemoteService
- * Signature: (Ljava/lang/String;)V
- */
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_ns_provider_ProviderService_nativeEnableRemoteService
-(JNIEnv *, jobject, jstring);
-
-/*
- * Class: org_iotivity_service_ns_provider_ProviderService
- * Method: nativeDisableRemoteService
- * Signature: (Ljava/lang/String;)V
- */
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_ns_provider_ProviderService_nativeDisableRemoteService
-(JNIEnv *, jobject, jstring);
-
-/*
- * Class: org_iotivity_service_ns_provider_ProviderService
- * Method: nativeSubscribeMQService
- * Signature: (Ljava/lang/String;Ljava/lang/String;)V
- */
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_ns_provider_ProviderService_nativeSubscribeMQService
-(JNIEnv *, jobject, jstring, jstring);
-
-/*
- * Class: org_iotivity_service_ns_provider_ProviderService
- * Method: nativeRegisterTopic
- * Signature: (Ljava/lang/String;)V
- */
-JNIEXPORT void JNICALL Java_org_iotivity_service_ns_provider_ProviderService_nativeRegisterTopic
-(JNIEnv *, jobject, jstring);
-
-/*
- * Class: org_iotivity_service_ns_provider_ProviderService
- * Method: nativeUnregisterTopic
- * Signature: (Ljava/lang/String;)V
- */
-JNIEXPORT void JNICALL Java_org_iotivity_service_ns_provider_ProviderService_nativeUnregisterTopic
-(JNIEnv *, jobject, jstring);
-
-/*
- * Class: org_iotivity_service_ns_provider_ProviderService
- * Method: nativeGetRegisteredTopicList
- * Signature: ()Lorg/iotivity/service/ns/common/TopicsList;
- */
-JNIEXPORT jobject JNICALL
-Java_org_iotivity_service_ns_provider_ProviderService_nativeGetRegisteredTopicList
-(JNIEnv *, jobject);
-
-/*
- * Class: org_iotivity_service_ns_provider_Consumer
- * Method: nativeAcceptSubscription
- * Signature: (Ljava/lang/String;Z)V
- */
-JNIEXPORT void JNICALL Java_org_iotivity_service_ns_provider_Consumer_nativeAcceptSubscription
-(JNIEnv *, jobject, jstring, jboolean);
-
-/*
- * Class: org_iotivity_service_ns_provider_Consumer
- * Method: nativeSetConsumerTopic
- * Signature: (Ljava/lang/String;Ljava/lang/String;)V
- */
-JNIEXPORT void JNICALL Java_org_iotivity_service_ns_provider_Consumer_nativeSetConsumerTopic
-(JNIEnv *, jobject, jstring, jstring);
-
-/*
- * Class: org_iotivity_service_ns_provider_Consumer
- * Method: nativeUnsetConsumerTopic
- * Signature: (Ljava/lang/String;Ljava/lang/String;)V
- */
-JNIEXPORT void JNICALL Java_org_iotivity_service_ns_provider_Consumer_nativeUnsetConsumerTopic
-(JNIEnv *, jobject, jstring, jstring);
-
-/*
- * Class: org_iotivity_service_ns_provider_Consumer
- * Method: nativeGetConsumerTopicList
- * Signature: (Ljava/lang/String;)Lorg/iotivity/service/ns/common/TopicsList;
- */
-JNIEXPORT jobject JNICALL
-Java_org_iotivity_service_ns_provider_Consumer_nativeGetConsumerTopicList
-(JNIEnv *, jobject, jstring);
-
-#ifdef __cplusplus
-}
-#endif
-#endif
-
-
+++ /dev/null
-/*
- * //******************************************************************
- * //
- * // Copyright 2015 Intel Corporation.
- * //
- * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- * //
- * // 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 ':notification-service'
+++ /dev/null
-*.iml\r
-.gradle\r
-/local.properties\r
-/.idea/workspace.xml\r
-/.idea/libraries\r
-.DS_Store\r
-/build\r
-/captures\r
+++ /dev/null
-#//******************************************************************
-#//
-#// Copyright 2016 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.
-#//
-#//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-import os
-import platform
-Import('env')
-
-android_home = env.get('ANDROID_HOME')
-
-ANDROID_TARGET_ARCH = env.get('TARGET_ARCH')
-if env.get('RELEASE'):
- ANDROID_RELEASE="release"
-else:
- ANDROID_RELEASE="debug"
-
-os.environ['ANDROID_HOME'] = env.get('ANDROID_HOME')
-os.environ['ANDROID_NDK_HOME'] = env.get('ANDROID_NDK')
-
-if not os.path.exists(android_home + '/platforms/android-21') or not os.path.exists(android_home + '/build-tools/20.0.0'):
- print '''
-***************************************** Info ********************************
-* Either 'Android API 21' is not installed or 'Android SDK Build Tools *
-* 20.0.0' is not installed. The Android SDK Manager will now open. Please *
-* be sure to deselect all options, then select the following 2 packages: *
-* 1. Under "Tools" select "Android SDK Build-tools" Revision 20. *
-* 2. Under "Android 5.0.1 (API 21)" select "SDK Platform" *
-* 3. Continue by selecting "Install 2 Packages" *
-* *
-* NOTE: If you have an http proxy, please press ctrl+c now and edit/create *
-* the following file in your $HOME directory as follows: *
-* *
-* Edit/Create file: "$HOME/.android/androidtool.cfg" *
-* *
-* http.proxyPort=<YOUR_PORT_NUMBER> *
-* sdkman.monitor.density=108 *
-* http.proxyHost=<YOUR_HTTP_PROXY_ADDRESS> *
-* sdkman.show.update.only=true *
-* sdkman.ask.adb.restart=false *
-* sdkman.force.http=true *
-* sdkman.show.updateonly=true *
-* *
-*******************************************************************************
-
-...Opening Android SDK Manager now. Once you are finished, the build will continue.
-'''
- os.system(android_home + '/tools/android')
-
-def ensure_libs(target, source, env):
- return target, [source,
- env.get('BUILD_DIR') + 'libnotification_provider_jni.so',
- env.get('BUILD_DIR') + 'libnotification_provider_wrapper.so',
- env.get('BUILD_DIR') + 'libnotification_provider.so',
- env.get('BUILD_DIR') + 'libnotification_consumer_jni.so',
- env.get('BUILD_DIR') + 'libnotification_consumer_wrapper.so',
- env.get('BUILD_DIR') + 'libnotification_consumer.so']
-
-jdk_env = Environment(ENV=os.environ)
-jdk_env['BUILDERS']['Gradle'] = Builder(action = env.get('ANDROID_GRADLE') +
- ' build -bservice/notification/examples/android/NotiConsumerExample/build.gradle -PTARGET_ARCH=%s -PRELEASE=%s --stacktrace' %(ANDROID_TARGET_ARCH, ANDROID_RELEASE),
- emitter = ensure_libs)
-jdk_env['BUILD_DIR'] = env.get('BUILD_DIR')
-cmdBuildNotificationConsumerApp=jdk_env.Gradle(target="app/apk",
- source=["app/src/main/java/org/iotivity/service/ns/sample/consumer/MainActivity.java",
- "app/src/main/java/org/iotivity/service/ns/sample/consumer/ConsumerSample.java"])
-jdk_env.Clean(cmdBuildNotificationConsumerApp, '#/service/notification/examples/android/NotiConsumerExample/build')
-Depends(cmdBuildNotificationConsumerApp, env.get('notificationAAR'))
+++ /dev/null
-apply plugin: 'com.android.application'
-
-android {
- compileSdkVersion 21
- buildToolsVersion "20.0.0"
-
- packagingOptions {
- pickFirst 'lib/armeabi/libocstack-jni.so'
- pickFirst 'lib/armeabi-v7a/libocstack-jni.so'
- pickFirst 'lib/x86/libocstack-jni.so'
- pickFirst 'lib/x86_64/libocstack-jni.so'
- pickFirst 'lib/arm64-v8a/libocstack-jni.so'
- pickFirst 'lib/armeabi/libresource_directory.so'
- pickFirst 'lib/armeabi-v7a/libresource_directory.so'
- pickFirst 'lib/x86/libresource_directory.so'
- pickFirst 'lib/x86_64/libresource_directory.so'
- pickFirst 'lib/arm64-v8a/libresource_directory.so'
- }
-
- defaultConfig {
- applicationId "sample.notification.service.iotivity.org.notificationconsumersample"
- minSdkVersion 21
- targetSdkVersion 21
- versionCode 1
- versionName "1.0"
- }
-
- lintOptions {
- abortOnError false
- }
-}
-
-dependencies {
- compile fileTree(include: ['*.jar'], dir: 'libs')
- compile ":iotivity-base-${TARGET_ARCH}-${RELEASE}@aar"
- compile ":iotivity-${TARGET_ARCH}-notification-service-${RELEASE}@aar"
-}
+++ /dev/null
-# Add project specific ProGuard rules here.\r
-# By default, the flags in this file are appended to flags specified\r
-# in D:\adt-bundle-windows-x86_64-20140321\sdk/tools/proguard/proguard-android.txt\r
-# You can edit the include path and order by changing the proguardFiles\r
-# directive in build.gradle.\r
-#\r
-# For more details, see\r
-# http://developer.android.com/guide/developing/tools/proguard.html\r
-\r
-# Add any project specific keep options here:\r
-\r
-# If your project uses WebView with JS, uncomment the following\r
-# and specify the fully qualified class name to the JavaScript interface\r
-# class:\r
-#-keepclassmembers class fqcn.of.javascript.interface.for.webview {\r
-# public *;\r
-#}\r
+++ /dev/null
-/*
-* Copyright 2016 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.iotivity.service.ns.sample.consumer;
-
-import android.app.Application;
-import android.content.Context;
-import android.support.test.runner.AndroidJUnit4;
-import android.test.ApplicationTestCase;
-import android.util.Log;
-
-import org.iotivity.base.ModeType;
-import org.iotivity.base.OcPlatform;
-import org.iotivity.base.PlatformConfig;
-import org.iotivity.base.QualityOfService;
-import org.iotivity.base.ServiceType;
-import org.iotivity.service.ns.common.Message;
-import org.iotivity.service.ns.common.NSException;
-import org.iotivity.service.ns.common.NSErrorCode;
-import org.iotivity.service.ns.common.Topic;
-import org.iotivity.service.ns.common.TopicsList;
-import org.iotivity.service.ns.common.SyncInfo;
-import org.iotivity.service.ns.consumer.ConsumerService;
-import org.iotivity.service.ns.provider.ProviderService;
-import org.iotivity.service.ns.consumer.Provider;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.util.Iterator;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-/**
- * To work on unit tests, switch the Test Artifact in the Build Variants view.
- */
-@RunWith(AndroidJUnit4.class)
-public class ExampleUnitTest extends ApplicationTestCase<Application> {
- public ExampleUnitTest() {
- super(Application.class);
- }
-
- private static Context mContext = null;
- private ProviderService gProviderRes;
- private ProviderSimulator gProviderSimul;
- private static ConsumerService gConsumerRes;
- private static DiscoveryCallbackListener disCb;
- private static ProviderCallbackListener provCb;
- CountDownLatch lockObject;
- Response response;
- private static String TAG = "ConsumerExample UnitTest";
-
- public void startBefore(boolean subControllability) {
- Log.i(TAG, "startConsumerBefore - IN");
- try {
- gConsumerRes.start(disCb);
- gProviderRes.start(gProviderSimul, gProviderSimul,
- subControllability, "nothing", false);
- lockObject.await(4000, TimeUnit.MILLISECONDS);
- } catch (Exception e) {
- e.printStackTrace();
- }
- Log.i(TAG, "startConsumerBefore - OUT");
- }
-
- public void startAfter(boolean subControllability) {
- Log.i(TAG, "startConsumerAfter - IN");
- try {
- gProviderRes.start(gProviderSimul, gProviderSimul,
- subControllability, "nothing", false);
- gConsumerRes.start(disCb);
- lockObject.await(4000, TimeUnit.MILLISECONDS);
- } catch (Exception e) {
- e.printStackTrace();
- }
- Log.i(TAG, "startConsumerAfter - OUT");
- }
-
- public void setListener(Provider mProvider) {
- try {
- mProvider.setListener(provCb, provCb, provCb);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- public void subscribe(Provider.ProviderState state) {
- lockObject = new CountDownLatch(1);
- response = new Response();
- provCb.set(lockObject, response);
- provCb.setState(state);
- Provider mProvider = disCb.getProvider();
- setListener(mProvider);
- try {
- if (!mProvider.isSubscribed()) {
- Log.i(TAG, "not subscribed");
- mProvider.subscribe();
- }
- lockObject.await(4000, TimeUnit.MILLISECONDS);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- public void unsubscribe() {
- lockObject = new CountDownLatch(1);
- response = new Response();
- provCb.set(lockObject, response);
- provCb.setState(Provider.ProviderState.STOPPED);
- Provider mProvider = disCb.getProvider();
- setListener(mProvider);
- try {
- if (mProvider.isSubscribed()) {
- Log.i(TAG, "subscribed");
- mProvider.unsubscribe();
- }
- lockObject.await(4000, TimeUnit.MILLISECONDS);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- public long sendMessage() {
- lockObject = new CountDownLatch(1);
- response = new Response();
- provCb.set(lockObject, response);
- org.iotivity.service.ns.common.Message msg = gProviderSimul
- .getMessage();
- long Id = msg.getMessageId();
- provCb.setId(Id);
- try {
- gProviderRes.sendMessage(msg);
- lockObject.await(4000, TimeUnit.MILLISECONDS);
- } catch (Exception e) {
- e.printStackTrace();
- }
- return Id;
- }
-
- public void sendSyncInfo(long id, SyncInfo.SyncType type) {
- try {
- lockObject = new CountDownLatch(1);
- response = new Response();
- provCb.set(lockObject, response);
- provCb.setType(type);
- gProviderRes.sendSyncInfo(id, type);
- lockObject.await(4000, TimeUnit.MILLISECONDS);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- public void providerSendSyncInfo(Provider provider, long id,
- SyncInfo.SyncType type) {
- try {
- lockObject = new CountDownLatch(1);
- response = new Response();
- provCb.set(lockObject, response);
- provCb.setType(type);
- provider.sendSyncInfo(id, type);
- lockObject.await(4000, TimeUnit.MILLISECONDS);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- public void registerTopic(String topic) {
- lockObject = new CountDownLatch(1);
- response = new Response();
- provCb.set(lockObject, response);
- provCb.setState(Provider.ProviderState.TOPIC);
- try {
- gProviderRes.registerTopic(topic);
- lockObject.await(4000, TimeUnit.MILLISECONDS);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- @BeforeClass
- public static void Initialize() {
- PlatformConfig platformConfig = new PlatformConfig(mContext,
- ServiceType.IN_PROC, ModeType.CLIENT_SERVER, "0.0.0.0",
- 0, // Uses randomly available port
- QualityOfService.LOW);
-
- OcPlatform.Configure(platformConfig);
- try {
- OcPlatform.stopPresence(); // Initialize OcPlatform
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- @Before
- public void SetUp() {
- Log.i(TAG, "SetUp - IN");
- disCb = new DiscoveryCallbackListener();
- provCb = new ProviderCallbackListener();
- gConsumerRes = ConsumerService.getInstance();
- gProviderRes = ProviderService.getInstance();
- gProviderSimul = new ProviderSimulator();
- lockObject = new CountDownLatch(1);
- response = new Response();
- disCb.set(lockObject, response);
- Log.i(TAG, "SetUp - OUT");
- }
-
- @After
- public void TearDown() {
- Log.i(TAG, "TearDown - IN");
- try {
- gConsumerRes.stop();
- gProviderRes.stop();
- lockObject = new CountDownLatch(1);
- lockObject.await(2000, TimeUnit.MILLISECONDS);
- } catch (Exception e) {
- e.printStackTrace();
- }
- Log.i(TAG, "TearDown - OUT");
- }
-
- @Test
- public void DiscoverProviderWithNonAccepterWhenStartedConsumerFirst() {
- startBefore(false);
- assertEquals(true, response.get());
- }
-
- @Test
- public void DiscoverProviderWithNonAccepterWhenStartedConsumerAfter() {
- startAfter(false);
- assertEquals(true, response.get());
- }
-
- @Test
- public void DiscoverProviderWithNonAccepterWhenRescan() {
- startAfter(false);
- assertEquals(true, response.get());
- try {
- gConsumerRes.rescanProvider();
- } catch (Exception e) {
- e.printStackTrace();
- }
- assertEquals(true, response.get());
- }
-
- @Test
- public void ExpectSubscribeSuccess() {
- startAfter(false);
- assertEquals(true, response.get());
-
- Provider.ProviderState state = Provider.ProviderState.ALLOW;
- subscribe(state);
- assertEquals(true, response.get());
- }
- @Test
- public void ExpectUnSubscribeSuccess() {
- startAfter(false);
- assertEquals(true, response.get());
-
- Provider.ProviderState state = Provider.ProviderState.ALLOW;
- subscribe(state);
- assertEquals(true, response.get());
- unsubscribe();
- assertEquals(true, response.get());
- }
- @Test
- public void ExpectReceiveNotification() {
- startAfter(false);
- assertEquals(true, response.get());
-
- Provider.ProviderState state = Provider.ProviderState.ALLOW;
- subscribe(state);
- assertEquals(true, response.get());
-
- sendMessage();
- assertEquals(true, response.get());
-
- }
-
- @Test
- public void DiscoverProviderWithAccepterisProvider() {
- startAfter(true);
- assertEquals(true, response.get());
- }
-
- @Test
- public void ExpectReceiveNotificationWithAccepterisProvider() {
- startAfter(true);
- assertEquals(true, response.get());
-
- Provider mProvider = disCb.getProvider();
- setListener(mProvider);
-
- sendMessage();
- assertEquals(true, response.get());
- }
-
- @Test
- public void ExpectCallbackReadCheckWhenProviderNotifySync() {
- startAfter(true);
- assertEquals(true, response.get());
-
- Provider mProvider = disCb.getProvider();
- setListener(mProvider);
-
- long id = sendMessage();
- assertEquals(true, response.get());
-
- sendSyncInfo(id, SyncInfo.SyncType.READ);
- assertEquals(true, response.get());
- }
-
- @Test
- public void ExpectCallbackDismissCheckWhenProviderNotifySync() {
- startAfter(true);
- assertEquals(true, response.get());
-
- Provider mProvider = disCb.getProvider();
- setListener(mProvider);
-
- long id = sendMessage();
- assertEquals(true, response.get());
-
- sendSyncInfo(id, SyncInfo.SyncType.DELETED);
- assertEquals(true, response.get());
- }
-
- @Test
- public void ExpectCallbackReadCheckWhenConsumerPostSync() {
- startAfter(true);
- assertEquals(true, response.get());
-
- Provider mProvider = disCb.getProvider();
- setListener(mProvider);
-
- long id = sendMessage();
- assertEquals(true, response.get());
-
- providerSendSyncInfo(mProvider, id, SyncInfo.SyncType.READ);
- assertEquals(true, response.get());
- }
-
- @Test
- public void ExpectCallbackDismissCheckWhenConsumerPostSync() {
- startAfter(true);
- assertEquals(true, response.get());
-
- Provider mProvider = disCb.getProvider();
- setListener(mProvider);
-
- long id = sendMessage();
- assertEquals(true, response.get());
-
- providerSendSyncInfo(mProvider, id, SyncInfo.SyncType.DELETED);
- assertEquals(true, response.get());
- }
-
- @Test
- public void ExpectCallbackTopicUpdated() {
- startAfter(true);
- assertEquals(true, response.get());
-
- Provider mProvider = disCb.getProvider();
- setListener(mProvider);
-
- registerTopic("OIC_TOPIC1");
- assertEquals(true, response.get());
- }
-
- @Test
- public void ExpectEQTopicList() {
- startAfter(true);
- assertEquals(true, response.get());
-
- Provider mProvider = disCb.getProvider();
- setListener(mProvider);
-
- try {
- registerTopic("OIC_TOPIC1");
- assertEquals(true, response.get());
- registerTopic("OIC_TOPIC2");
- assertEquals(true, response.get());
- registerTopic("OIC_TOPIC3");
- assertEquals(true, response.get());
-
- response = new Response();
- Iterator<Topic> it = mProvider.getTopicList().getTopicsList()
- .iterator();
- Iterator<Topic> it2 = gProviderRes.getRegisteredTopicList()
- .getTopicsList().iterator();
- while (it.hasNext()) {
- Topic element = it.next();
- Topic element2 = it2.next();
- Log.i(TAG, element2.getTopicName());
- if (!element.getTopicName().equals(element2.getTopicName())) {
- response.set(false);
- break;
- }
- response.set(true);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- assertEquals(true, response.get());
- }
-
- @Test
- public void ExpectFailUpdateTopicOnConsumer() {
- startAfter(true);
- assertEquals(true, response.get());
-
- Provider mProvider = disCb.getProvider();
- setListener(mProvider);
-
- registerTopic("OIC_TOPIC1");
- assertEquals(true, response.get());
-
- try {
- TopicsList list = mProvider.getTopicList();
- Iterator<Topic> it = list.getTopicsList().iterator();
- while (it.hasNext()) {
- Topic element = it.next();
- element.setState(Topic.TopicState.SUBSCRIBED);
- }
- mProvider.updateTopicList(list);
- } catch (NSException e) {
- e.printStackTrace();
- assertEquals(NSErrorCode.ERROR, e.getErrorCode());
- }
- }
-
- @Test
- public void ExpectCallbackStoppedProvider() {
- startAfter(true);
- assertEquals(true, response.get());
-
- Provider mProvider = disCb.getProvider();
- setListener(mProvider);
-
- lockObject = new CountDownLatch(1);
- response = new Response();
- provCb.set(lockObject, response);
- provCb.setState(Provider.ProviderState.STOPPED);
-
- try {
- gProviderRes.stop();
- lockObject.await(4000, TimeUnit.MILLISECONDS);
- } catch (Exception e) {
- e.printStackTrace();
- }
-
- assertEquals(true, response.get());
-
- }
-}
-
-class DiscoveryCallbackListener
- implements ConsumerService.OnProviderDiscoveredListener {
- private CountDownLatch mLockObject;
- private Response mResponse;
- private Provider mProvider;
- private static String TAG = "UnitTest DiscoveryCallbackListener";
-
- public void set(CountDownLatch lockObject, Response response) {
- mLockObject = lockObject;
- mResponse = response;
- }
-
- public Provider getProvider() {
- return mProvider;
- }
-
- @Override
- public void onProviderDiscovered(Provider provider) {
- Log.i(TAG, provider.getProviderId());
- mProvider = provider;
- if (mResponse != null) {
- Log.i(TAG, "onProviderDiscovered: Lock released");
- mResponse.set(true);
- mLockObject.countDown();
- }
- }
-}
-
-class ProviderCallbackListener implements Provider.OnProviderStateListener,
- Provider.OnMessageReceivedListener, Provider.OnSyncInfoReceivedListener {
-
- private CountDownLatch mLockObject;
- private Response mResponse;
- private Provider.ProviderState mState;
- private SyncInfo.SyncType mType;
- private long mId;
- private static String TAG = "UnitTest ProviderCallbackListener";
-
- public void set(CountDownLatch lockObject, Response response) {
- mLockObject = lockObject;
- mResponse = response;
- }
-
- public void setState(Provider.ProviderState state) {
- mState = state;
- }
-
- public void setId(long id) {
- mId = id;
- }
-
- void setType(SyncInfo.SyncType type) {
- mType = type;
- }
-
- @Override
- public void onProviderStateReceived(Provider.ProviderState state) {
- Log.i(TAG, "onProviderStateReceived: " + state);
- if (mState == state) {
- Log.i(TAG, "onProviderStateReceived: Lock released");
- mResponse.set(true);
- mLockObject.countDown();
- }
-
- }
-
- @Override
- public void onMessageReceived(org.iotivity.service.ns.common.Message msg) {
- Log.i(TAG, "onMessageReceived: " + msg.getMessageId());
- if (mId == msg.getMessageId()) {
- Log.i(TAG, "onMessageReceived: Lock released");
- mResponse.set(true);
- mLockObject.countDown();
- }
- }
-
- @Override
- public void onSyncInfoReceived(SyncInfo syncInfo) {
- Log.i(TAG, "onSyncInfoReceived: " + syncInfo.getState());
- if (mType == syncInfo.getState()) {
- Log.i(TAG, "onSyncInfoReceived: Lock released");
- mResponse.set(true);
- mLockObject.countDown();
- }
- }
-}
-
-class Response {
- private boolean state;
-
- Response() {
- state = false;
- }
-
- public void set(boolean val) {
- state = val;
- }
-
- public boolean get() {
- return state;
- }
-}
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2016 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.iotivity.service.ns.sample.consumer;
-
-import android.util.Log;
-
-import org.iotivity.service.ns.common.MediaContents;
-import org.iotivity.service.ns.common.Message;
-import org.iotivity.service.ns.common.SyncInfo;
-import org.iotivity.service.ns.provider.Consumer;
-import org.iotivity.service.ns.provider.ProviderService;
-
-class ProviderSimulator
- implements ProviderService.OnMessageSynchronizedListener,
- ProviderService.OnConsumerSubscribedListener {
- private String TAG = "Provider Simulator";
- private Consumer gConsumer;
-
- @Override
- public void onMessageSynchronized(SyncInfo syncInfo) {
- Log.i(TAG, "Notification onMessageSynchronized: ");
- }
-
- @Override
- public void onConsumerSubscribed(Consumer consumer) {
- gConsumer = consumer;
- try {
- gConsumer.acceptSubscription(true);
- Log.i(TAG, "Notification AcceptSubscription" );
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- public Message getMessage() {
- try {
- Message msg = ProviderService.getInstance().createMessage();
- msg.setTitle("Title");
- msg.setSourceName("provider");
- msg.setContentText("notification");
- MediaContents media = new MediaContents("new");
- msg.setMediaContents(media);
- return msg;
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }
-
-}
+++ /dev/null
-<?xml version="1.0" encoding="utf-8"?>\r
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"\r
- package="org.iotivity.service.ns.sample.consumer">\r
-\r
- <uses-feature android:name="android.hardware.nfc" />\r
- <uses-permission android:name="android.permission.READ_PHONE_STATE" />\r
- <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />\r
- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />\r
- <uses-permission android:name="android.permission.BLUETOOTH"/>\r
- <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>\r
- <uses-permission android:name="android.permission.INTERNET"/>\r
- <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>\r
- <uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE"/>\r
- <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>\r
- <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>\r
- <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>\r
- <uses-permission android:name="android.permission.NFC" />\r
-\r
- <application\r
- android:allowBackup="true"\r
- android:icon="@mipmap/ic_launcher"\r
- android:label="@string/app_name"\r
- android:supportsRtl="true"\r
- android:theme="@style/AppTheme">\r
- <activity android:name=".MainActivity">\r
- <intent-filter>\r
- <action android:name="android.intent.action.MAIN" />\r
-\r
- <category android:name="android.intent.category.LAUNCHER" />\r
- </intent-filter>\r
- </activity>\r
- <activity android:name=".LoginActivity" />\r
-\r
- </application>\r
-\r
-</manifest>\r
+++ /dev/null
-/******************************************************************
- * Copyright 2016 Samsung Electronics All Rights Reserved.
- * <p>
- * <p>
- * <p>
- * 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
- * <p>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p>
- * 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.iotivity.service.ns.sample.consumer;
-
-import android.content.Context;
-import android.os.Handler;
-import android.os.Message;
-import android.util.Log;
-
-import org.iotivity.base.ModeType;
-import org.iotivity.base.OcPlatform;
-import org.iotivity.base.PlatformConfig;
-import org.iotivity.base.QualityOfService;
-import org.iotivity.base.ServiceType;
-import org.iotivity.service.ns.common.NSException;
-import org.iotivity.service.ns.common.SyncInfo;
-import org.iotivity.service.ns.common.TopicsList;
-import org.iotivity.service.ns.common.Topic;
-import org.iotivity.service.ns.consumer.ConsumerService;
-import org.iotivity.service.ns.consumer.Provider;
-
-public class ConsumerSample
- implements ConsumerService.OnProviderDiscoveredListener,
- Provider.OnProviderStateListener, Provider.OnMessageReceivedListener,
- Provider.OnSyncInfoReceivedListener {
- private static final String TAG = "NS_CONSUMER_SAMPLE";
-
- private Context mContext = null;
- private ConsumerService consumerService = null;
- private boolean mAcceptor = true;
- private Provider mProvider = null;
-
- private Handler mHandler = null;
-
- private static final int PROVIDER_DISCOVERED = 1;
- private static final int STATE_CHANGED = 2;
- private static final int MESSAGE_RECEIVED = 3;
- private static final int SYNCINFO_RECEIVED = 4;
- private static final int TOPICS_RECEIVED = 5;
-
- public ConsumerSample(Context context) {
- Log.i(TAG, "Create consumer sample Instance");
-
- this.mContext = context;
- consumerService = new ConsumerService();
- }
-
- public void setHandler(Handler handler) {
- this.mHandler = handler;
- }
-
- public boolean getAcceptor() {
- return mAcceptor;
- }
-
- private void configurePlatform() {
-
- PlatformConfig platformConfig = new PlatformConfig(mContext,
- ServiceType.IN_PROC, ModeType.CLIENT_SERVER, "0.0.0.0",
- 0, // Uses randomly available port
- QualityOfService.LOW);
-
- Log.i(TAG, "Configuring platform.");
- OcPlatform.Configure(platformConfig);
- try {
- OcPlatform.stopPresence(); // Initialize OcPlatform
- } catch (Exception e) {
- Log.e(TAG, "Exception: stopping presence when configuration step: "
- + e);
- }
- Log.i(TAG, "Configuration done Successfully");
- }
-
- public void startNotificationConsumer() {
- configurePlatform();
- try {
- consumerService.start(this);
- } catch (Exception e) {
- Log.e(TAG, "Exception: startNotificationConsumer : " + e);
- }
- }
-
- public void stopNotificationConsumer() {
- try {
- consumerService.stop();
- mProvider = null;
- } catch (Exception e) {
- Log.e(TAG, "Exception: stopNotificationConsumer : " + e);
- }
- }
-
- public void enableRemoteService(String serverAddress) {
- try {
- consumerService.enableRemoteService(serverAddress);
- } catch (NSException e) {
- Log.e(TAG, "NSException: enableRemoteService : " + e);
- }
- }
-
- public void subscribeMQService(String servAdd, String topicName) {
- Log.i(TAG, "SubscribeMQService - IN");
- try {
- consumerService.subscribeMQService(servAdd, topicName);
- } catch (Exception e) {
- Log.e(TAG, "Exception: subscribeMQService : " + e);
- }
- Log.i(TAG, "SubscribeMQService - OUT");
- return;
- }
-
- public void rescanProvider() {
- try {
- consumerService.rescanProvider();
- } catch (Exception e) {
- Log.e(TAG, "Exception: rescanProvider : " + e);
- }
- }
-
- public void subscribe() {
- try {
- mProvider.subscribe();
- Log.i(TAG, "Notification consumer subscribe: " );
- } catch (Exception e) {
- Log.e(TAG, "Exception: subscribe : " + e);
- }
- }
-
- public void unsubscribe() {
- try {
- mProvider.unsubscribe();
- Log.i(TAG, "Notification consumer unsubscribe: ");
- } catch (Exception e) {
- Log.e(TAG, "Exception: unsubscribe : " + e);
- }
- }
- public void getTopicsList() {
- if (mProvider != null) {
- try {
- TopicsList topicsList = mProvider.getTopicList();
- StringBuilder stringBuilder = new StringBuilder();
- stringBuilder.append("TopicList Received :");
- for (Topic topic : topicsList.getTopicsList()) {
- Log.i(TAG, "Topic Name : " + topic.getTopicName());
- Log.i(TAG, "Topic State : " + topic.getState());
- stringBuilder
- .append("\nTopic Name : " + topic.getTopicName());
- stringBuilder.append("\nTopic State : " + topic.getState());
- }
- Message msg = mHandler.obtainMessage(TOPICS_RECEIVED,
- stringBuilder.toString());
- mHandler.sendMessage(msg);
- } catch (Exception e) {
- Log.e(TAG, "Exception: getTopicsList : " + e);
- }
- } else {
- Log.e(TAG, "getTopicsList Provider NULL");
- }
- }
-
- public void updateTopicList(TopicsList topicsList) {
- if (mProvider != null) {
- try {
- mProvider.updateTopicList(topicsList);
- } catch (Exception e) {
- Log.e(TAG, "Exception: updateTopicList : " + e);
- }
- } else {
- Log.e(TAG, "updateTopicList Provider NULL");
- }
- }
-
- @Override
- public void onProviderDiscovered(Provider provider) {
- Log.i(TAG, "onProviderDiscovered");
- if (provider == null) {
- Log.e(TAG, "providerID is Null ");
- return;
- }
- mProvider = provider;
- Log.i(TAG, "Provider ID: " + provider.getProviderId());
- Message msg = mHandler.obtainMessage(PROVIDER_DISCOVERED,
- "Provider Discovered Id: " + provider.getProviderId());
- mHandler.sendMessage(msg);
- try {
- Log.i(TAG, "setListeners to Discovered Provider");
- provider.setListener(this, this, this);
- Log.i(TAG, "setListeners done");
- if (!provider.isSubscribed()) {
- Log.i(TAG, "Provider not subscribed. Acceptor is Consumer");
- mAcceptor = false;
- provider.subscribe();
- } else {
- Log.i(TAG,
- "Provider is already subscribed. Acceptor is Provider");
- mAcceptor = true;
- }
- } catch (Exception e) {
- Log.e(TAG, "Exception : " + e);
- }
- }
-
- @Override
- public void onProviderStateReceived(Provider.ProviderState state) {
- Log.i(TAG, "onProviderStateReceived");
-
- Log.i(TAG, "ProviderState Received : " + state);
- Message msg = mHandler.obtainMessage(STATE_CHANGED,
- "ProviderState Received : " + state);
- mHandler.sendMessage(msg);
- }
-
- @Override
- public void onMessageReceived(
- org.iotivity.service.ns.common.Message message) {
- Log.i(TAG, "onMessageReceived");
-
- Log.i(TAG, "Message Id: " + message.getMessageId());
- Log.i(TAG, "Message title: " + message.getTitle());
- Log.i(TAG, "Message Content: " + message.getContentText());
- Log.i(TAG, "Message Topic: " + message.getTopic());
- Log.i(TAG, "Message Source: " + message.getSourceName());
-
- Message msg = mHandler.obtainMessage(MESSAGE_RECEIVED,
- "Message Id: " + message.getMessageId() + "\n"
- + "Message title: " + message.getTitle() + "\n"
- + "Message Content: " + message.getContentText() + "\n"
- + "Message Topic: " + message.getTopic() + "\n"
- + "Message Source: " + message.getSourceName());
- mHandler.sendMessage(msg);
- try {
- Log.i(TAG, "send READ syncInfo");
- mProvider.sendSyncInfo(message.getMessageId(),
- SyncInfo.SyncType.READ);
- } catch (Exception e) {
- Log.e(TAG, "Exception : " + e);
- }
- }
-
- @Override
- public void onSyncInfoReceived(SyncInfo sync) {
- Log.i(TAG, "onSyncInfoReceived");
-
- Log.i(TAG, "Sync Id: " + sync.getMessageId());
- Log.i(TAG, "Sync STATE: " + sync.getState());
- Message msg = mHandler.obtainMessage(SYNCINFO_RECEIVED,
- "Sync Id: " + sync.getMessageId() + "\n" + "Sync STATE: "
- + sync.getState());
- mHandler.sendMessage(msg);
- }
-}
+++ /dev/null
-/*
- * ******************************************************************
- *
- * Copyright 2016 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.iotivity.service.ns.sample.consumer;
-
-import android.app.Activity;
-import android.app.Dialog;
-import android.content.Context;
-import android.content.Intent;
-import android.net.UrlQuerySanitizer;
-import android.os.Bundle;
-import android.util.Log;
-import android.view.View;
-import android.webkit.WebView;
-import android.webkit.WebViewClient;
-import android.widget.Button;
-import android.widget.EditText;
-
-/**
- * This class is for login to the provider. Can be get auth code via web page.
- */
-public class LoginActivity extends Activity {
- private static final String TAG = "OIC_SIMPLE_LOGIN";
-
- private final Context context = this;
- private WebView mWebView = null;
- private static String loginAccount = null;
- private static String mAuthProvider = null;
-
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_login);
-
- final Dialog dialog = new Dialog(context);
- dialog.setContentView(R.layout.dialog_auth);
- dialog.setTitle("Login Details");
- final EditText auth = (EditText) dialog.findViewById(R.id.EditTextAuth);
- final EditText url = (EditText) dialog.findViewById(R.id.EditTextUrl);
- if (loginAccount != null && mAuthProvider != null) {
- url.setText(loginAccount);
- auth.setText(mAuthProvider);
- }
-
- Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
- dialog.setCanceledOnTouchOutside(false);
- dialogButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- dialog.dismiss();
- loginAccount = url.getText().toString();
- mAuthProvider = auth.getText().toString();
-
- mWebView = (WebView) findViewById(R.id.webView);
- mWebView.setInitialScale(200);
- mWebView.getSettings().setJavaScriptEnabled(true);
- mWebView.getSettings().setBuiltInZoomControls(true);
- mWebView.setWebViewClient(new WebViewClientClass());
-
- mWebView.loadUrl(loginAccount);
- }
- });
- dialog.show();
- }
-
- public void onDestroy() {
- super.onDestroy();
- }
-
- private class WebViewClientClass extends WebViewClient {
-
- @Override
- public void onPageFinished(WebView view, String url) {
- Log.i(TAG,
- "onPageFinished!!! Response received: called url=" + url);
-
- if (url.contains("code") && url.contains("code_expires_in")) {
-
- mWebView.setVisibility(View.INVISIBLE);
-
- // parsing url
- UrlQuerySanitizer sanitizer = new UrlQuerySanitizer();
- sanitizer.setAllowUnregisteredParamaters(true);
- sanitizer.parseUrl(url);
-
- String mAuthCode = sanitizer.getValue("code");
- Log.i(TAG, "onPageFinished!!! authCode=" + mAuthCode);
-
- Intent intent = getIntent();
- intent.putExtra("authCode", mAuthCode);
- intent.putExtra("authProvider", mAuthProvider);
- setResult(RESULT_OK, intent);
-
- finish();
- }
- }
- }
-}
+++ /dev/null
-/******************************************************************
- * Copyright 2016 Samsung Electronics All Rights Reserved.
- * <p>
- * <p>
- * <p>
- * 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
- * <p>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p>
- * 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.iotivity.service.ns.sample.consumer;
-
-import android.app.Dialog;
-import android.content.Context;
-import android.content.Intent;
-import android.os.Bundle;
-import android.os.Handler;
-import android.os.Message;
-import android.app.Activity;
-import android.util.Log;
-import android.view.View;
-import android.widget.Button;
-import android.widget.EditText;
-import android.widget.TextView;
-import android.widget.Toast;
-
-import org.iotivity.base.ErrorCode;
-import org.iotivity.base.OcAccountManager;
-import org.iotivity.base.OcConnectivityType;
-import org.iotivity.base.OcException;
-import org.iotivity.base.OcHeaderOption;
-import org.iotivity.base.OcPlatform;
-import org.iotivity.base.OcRepresentation;
-import org.iotivity.base.OcResource;
-import org.iotivity.service.ns.common.TopicsList;
-import org.iotivity.service.ns.common.Topic;
-
-import java.util.Arrays;
-import java.util.EnumSet;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-public class MainActivity extends Activity
- implements OcAccountManager.OnPostListener {
- private final String TAG = "NS_MAIN_ACTIVITY";
- private final int REQUEST_LOGIN = 1;
- private static final String CI_SERVER_PREFIX = "coap+tcp://";
- private final Context context = this;
-
- public static String deviceID = null;
- public static String CIServer = null;
- public static String RemoteAddress = null;
- public static String MQCloudAddress = null;
- public static String MQCloudTopic = null;
-
- private Button btnStart;
- private Button btnStop;
- private Button btnRescan;
- private Button btnSubscribe;
- private Button btnUnsubscribe;
- private Button btnEnableRemoteService;
- private Button btnGetTopicList;
- private Button btnUpdateTopicList;
- private Button btnClearLog;
- private static TextView TvLog;
- private Button signUp, signIn, signOut;
- private Button subscribeMQ;
-
- private boolean isStarted = false;
-
- private ConsumerSample mConsumerSample = null;
- private OcAccountManager mAccountManager;
- String mAuthCode;
- String mAuthProvider;
- String mRefreshtoken;
- String mUserID;
- String mAccessToken;
-
- private static final int PROVIDER_DISCOVERED = 1;
- private static final int STATE_CHANGED = 2;
- private static final int MESSAGE_RECEIVED = 3;
- private static final int SYNCINFO_RECEIVED = 4;
- private static final int TOPICS_RECEIVED = 5;
-
- public static Handler mHandler = new Handler() {
- @Override
- public void handleMessage(Message msg) {
- switch (msg.what) {
- case PROVIDER_DISCOVERED: {
- String providerId = (String) msg.obj;
- if (providerId != null) {
- TvLog.append(providerId + "\n");
- }
- break;
- }
- case STATE_CHANGED: {
- String state = (String) msg.obj;
- if (state != null) {
- TvLog.append(state + "\n");
- }
- break;
- }
- case MESSAGE_RECEIVED: {
- String message = (String) msg.obj;
- if (message != null) {
- TvLog.append(message + "\n");
- }
- break;
- }
- case SYNCINFO_RECEIVED: {
- String sync = (String) msg.obj;
- if (sync != null) {
- TvLog.append(sync + "\n");
- }
- break;
- }
- case TOPICS_RECEIVED: {
- String topicList = (String) msg.obj;
- if (topicList != null) {
- TvLog.append(topicList + "\n");
- }
- break;
- }
- default:
- break;
- }
- }
- };
-
- public void showToast(final String toast) {
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- Toast.makeText(getApplicationContext(), toast,
- Toast.LENGTH_SHORT).show();
- }
- });
- }
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
-
- btnStart = (Button) findViewById(R.id.BtnStart);
- btnStop = (Button) findViewById(R.id.BtnStop);
- btnRescan = (Button) findViewById(R.id.BtnRescan);
- btnSubscribe = (Button) findViewById(R.id.BtnSubscribe);
- btnUnsubscribe = (Button) findViewById(R.id.BtnUnsubscribe);
- btnEnableRemoteService = (Button) findViewById(
- R.id.BtnEnableRemoteService);
- btnGetTopicList = (Button) findViewById(R.id.BtnGetTopicList);
- btnUpdateTopicList = (Button) findViewById(R.id.BtnUpdateTopicList);
- btnClearLog = (Button) findViewById(R.id.BtnClearLog);
-
- signUp = (Button) findViewById(R.id.signup);
- signIn = (Button) findViewById(R.id.signin);
- signOut = (Button) findViewById(R.id.signout);
- subscribeMQ = (Button) findViewById(R.id.subscribeMQService);
- TvLog = (TextView) findViewById(R.id.TvLog);
-
- btnStart.setOnClickListener(mClickListener);
- btnStop.setOnClickListener(mClickListener);
- btnRescan.setOnClickListener(mClickListener);
- btnEnableRemoteService.setOnClickListener(mClickListener);
- btnGetTopicList.setOnClickListener(mClickListener);
- btnUpdateTopicList.setOnClickListener(mClickListener);
- btnClearLog.setOnClickListener(mClickListener);
-
- signIn.setEnabled(false);
- signOut.setEnabled(false);
- btnEnableRemoteService.setEnabled(false);
-
- btnSubscribe.setOnClickListener(mClickListener);
- btnUnsubscribe.setOnClickListener(mClickListener);
- signUp.setOnClickListener(mClickListener);
- signIn.setOnClickListener(mClickListener);
- signOut.setOnClickListener(mClickListener);
- subscribeMQ.setOnClickListener(mClickListener);
-
- mConsumerSample = new ConsumerSample(getApplicationContext());
- mConsumerSample.setHandler(mHandler);
- }
-
- @Override
- protected void onDestroy() {
- if (isStarted)
- mConsumerSample.stopNotificationConsumer();
- super.onDestroy();
- }
-
- Button.OnClickListener mClickListener = new View.OnClickListener() {
- public void onClick(View v) {
- switch (v.getId()) {
- case R.id.BtnStart: {
- if (!isStarted) {
- Log.i(TAG, "Start NS Consumer Service");
-
- TvLog.setText("Start NS-Consumer\n");
- mConsumerSample.startNotificationConsumer();
- isStarted = true;
- } else {
- Log.e(TAG, "NS Consumer Service has already started");
- showToast("Error : Service has already started");
- }
- }
- break;
-
- case R.id.BtnStop: {
- if (!isStarted) {
- Log.e(TAG,
- "Fail to stop service. Service has not been started");
- showToast("Error : Service has not been started");
- break;
- }
- TvLog.append("Stop NS-Consumer\n");
- mConsumerSample.stopNotificationConsumer();
- isStarted = false;
- }
- break;
- case R.id.BtnRescan: {
- if (!isStarted) {
- Log.e(TAG,
- "Fail to rescan. Service has not been started");
- showToast("Error : Service has not been started");
- break;
- }
- TvLog.append("Rescan NS-Consumer\n");
- mConsumerSample.rescanProvider();
- }
- break;
- case R.id.BtnSubscribe: {
- if (!isStarted) {
- Log.e(TAG,
- "Fail to Subscribe. Service has not been started");
- showToast("Error : Service has not been started");
- break;
- }
- TvLog.append("Subscribe NS-Consumer\n");
- mConsumerSample.subscribe();
- }
- break;
- case R.id.BtnUnsubscribe: {
- if (!isStarted) {
- Log.e(TAG,
- "Fail to Unsubscribe. Service has not been started");
- showToast("Error : Service has not been started");
- break;
- }
- TvLog.append("Unsubscribe NS-Consumer\n");
- mConsumerSample.unsubscribe();
- }
- break;
- case R.id.BtnEnableRemoteService: {
- if (!isStarted) {
- Log.e(TAG,
- "Fail to Enable RemoteService. Service has not been started");
- showToast("Error : Service has not been started");
- break;
- }
- TvLog.append("EnableRemoteService NS-Consumer\n");
- mConsumerSample.enableRemoteService(RemoteAddress);
- }
- break;
- case R.id.BtnGetTopicList: {
- if (!isStarted) {
- Log.e(TAG,
- "Fail to GetTopicList. Service has not been started");
- showToast("Error : Service has not been started");
- break;
- }
- TvLog.append("GetTopicList NS-Consumer\n");
- mConsumerSample.getTopicsList();
- }
- break;
- case R.id.BtnUpdateTopicList: {
- if (!isStarted) {
- Log.e(TAG,
- "Fail to UpdateTopicList. Service has not been started");
- showToast("Error : Service has not been started");
- break;
- }
- if (mConsumerSample.getAcceptor()) {
- Log.e(TAG,
- "Operation Not Allowed. ProviderService Acceptor is not Consumer");
- showToast(
- "Operation Not Allowed. ProviderService Acceptor is not Consumer");
- break;
- }
- TvLog.append("UpdateTopicList NS-Consumer\n");
-
- TopicsList topicList = new TopicsList();
- topicList.addTopic("OCF_TOPIC1",
- Topic.TopicState.SUBSCRIBED);
- topicList.addTopic("OCF_TOPIC2",
- Topic.TopicState.SUBSCRIBED);
- topicList.addTopic("OCF_TOPIC3",
- Topic.TopicState.UNSUBSCRIBED);
-
- mConsumerSample.updateTopicList(topicList);
- }
- break;
- case R.id.BtnClearLog: {
- TvLog.setText("");
- }
- break;
- case R.id.signup: {
- if (isStarted == false) {
- Log.e(TAG, "Fail to Sign Up");
- showToast("Start ConsumerService First");
- break;
- }
- TvLog.append("Initiating SignUp\n");
- signUp();
- }
- break;
- case R.id.signin: {
- if (isStarted == false) {
- Log.e(TAG, "Fail to Sign In");
- showToast("Start ConsumerService First");
- break;
- }
- TvLog.append("Initiating SignIn\n");
- signIn();
- }
- break;
- case R.id.signout: {
- if (isStarted == false) {
- Log.e(TAG, "Fail to Sign out");
- showToast("Start ConsumerService First");
- break;
- }
- TvLog.append("Initiating SignOut\n");
- signOut();
- }
- break;
- case R.id.subscribeMQService: {
- if (isStarted == false) {
- Log.e(TAG, "Fail to SubscribeMQService");
- showToast("Start ProviderService First");
- break;
- }
- final Dialog dialog = new Dialog(context);
- dialog.setContentView(R.layout.dialog_mq);
- dialog.setTitle("MQ Cloud Service Details");
-
- final EditText ip = (EditText) dialog
- .findViewById(R.id.EditTextIp);
- final EditText mqTopic = (EditText) dialog
- .findViewById(R.id.EditTextMqTopic);
- if (MQCloudAddress != null && MQCloudTopic != null) {
- ip.setText(MQCloudAddress);
- mqTopic.setText(MQCloudTopic);
- }
-
- Button dialogButton = (Button) dialog
- .findViewById(R.id.mqButtonOK);
-
- dialogButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- dialog.dismiss();
- MQCloudAddress = ip.getText().toString();
- MQCloudTopic = mqTopic.getText().toString();
- mConsumerSample.subscribeMQService(
- MQCloudAddress, MQCloudTopic);
- TvLog.append("SubscribeMQService success\n");
- }
- });
- dialog.show();
- }
- break;
- }
- }
- };
-
- public void logMessage(final String text) {
- runOnUiThread(new Runnable() {
- public void run() {
- Message msg = new Message();
- msg.obj = text;
- TvLog.append(text + "\n");
- }
- });
- Log.i(TAG, text);
- }
-
- OcAccountManager.OnPostListener onSignUp = new OcAccountManager.OnPostListener() {
- @Override
- public synchronized void onPostCompleted(List<OcHeaderOption> list,
- OcRepresentation ocRepresentation) {
- logMessage("signUp was successful");
- runOnUiThread(new Runnable() {
- public void run() {
- signIn.setEnabled(true);
- signUp.setEnabled(false);
- }
- });
- try {
- mUserID = ocRepresentation.getValue("uid");
- mAccessToken = ocRepresentation.getValue("accesstoken");
- mRefreshtoken = ocRepresentation.getValue("refreshtoken");
-
- logMessage("\tuserID: " + mUserID);
- logMessage("\taccessToken: " + mAccessToken);
- logMessage("\trefreshToken: " + mRefreshtoken);
-
- if (ocRepresentation.hasAttribute("expiresin")) {
- int expiresIn = ocRepresentation.getValue("expiresin");
- logMessage("\texpiresIn: " + expiresIn);
- }
- } catch (OcException e) {
- Log.e(TAG, e.toString());
- }
- }
-
- @Override
- public synchronized void onPostFailed(Throwable throwable) {
- logMessage("Failed to signUp");
- if (throwable instanceof OcException) {
- OcException ocEx = (OcException) throwable;
- Log.e(TAG, ocEx.toString());
- ErrorCode errCode = ocEx.getErrorCode();
- logMessage("Error code: " + errCode);
- }
- }
- };
-
- OcAccountManager.OnPostListener onSignIn = new OcAccountManager.OnPostListener() {
- @Override
- public synchronized void onPostCompleted(List<OcHeaderOption> list,
- OcRepresentation ocRepresentation) {
- logMessage("signIn was successful");
- runOnUiThread(new Runnable() {
- public void run() {
- signIn.setEnabled(false);
- signOut.setEnabled(true);
- btnEnableRemoteService.setEnabled(true);
- }
- });
-
- }
-
- @Override
- public synchronized void onPostFailed(Throwable throwable) {
- logMessage("Failed to signIn");
- if (throwable instanceof OcException) {
- OcException ocEx = (OcException) throwable;
- Log.e(TAG, ocEx.toString());
- ErrorCode errCode = ocEx.getErrorCode();
- logMessage("Error code: " + errCode);
- if (ErrorCode.UNAUTHORIZED_REQ != errCode) {
- refreshToken();
- }
- }
- }
- };
-
- OcAccountManager.OnPostListener onSignOut = new OcAccountManager.OnPostListener() {
- @Override
- public synchronized void onPostCompleted(List<OcHeaderOption> list,
- OcRepresentation ocRepresentation) {
- logMessage("signOut was successful");
- runOnUiThread(new Runnable() {
- public void run() {
- signIn.setEnabled(true);
- signOut.setEnabled(false);
- btnEnableRemoteService.setEnabled(false);
- }
- });
-
- }
-
- @Override
- public synchronized void onPostFailed(Throwable throwable) {
- logMessage("Failed to signOut");
- if (throwable instanceof OcException) {
- OcException ocEx = (OcException) throwable;
- Log.e(TAG, ocEx.toString());
- ErrorCode errCode = ocEx.getErrorCode();
- logMessage("Error code: " + errCode);
- if (ErrorCode.UNAUTHORIZED_REQ != errCode) {
- refreshToken();
- }
- }
- }
- };
-
-
- @Override
- public void onPostCompleted(List<OcHeaderOption> ocHeaderOptions,
- OcRepresentation ocRepresentation) {
-
- }
-
- @Override
- public void onPostFailed(Throwable throwable) {
-
- }
-
- private void signIn() {
- try {
- if (mAccountManager == null) {
- mAccountManager = OcPlatform.constructAccountManagerObject(
- CIServer,
- EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP));
- }
-
- mAccountManager.signIn(mUserID, mAccessToken, onSignIn);
- } catch (OcException e) {
- e.printStackTrace();
- }
- }
-
- private void signOut() {
- try {
- logMessage("signOut");
- if (mAccountManager == null) {
- try {
- mAccountManager = OcPlatform.constructAccountManagerObject(
- CIServer,
- EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP));
- } catch (OcException e) {
- e.printStackTrace();
- }
- }
- mAccountManager.signOut(mAccessToken, onSignOut);
- signIn.setEnabled(false);
- signUp.setEnabled(true);
- btnEnableRemoteService.setEnabled(false);
- logMessage("signOut Successful");
- } catch (OcException e) {
- e.printStackTrace();
- }
- }
-
- private void signUp() {
- Intent intentLogin = new Intent(this, LoginActivity.class);
- startActivityForResult(intentLogin, REQUEST_LOGIN);
- }
-
- @Override
- public void onActivityResult(int requestCode, int resultCode, Intent data) {
- super.onActivityResult(requestCode, resultCode, data);
- if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_LOGIN) {
- mAuthCode = data.getStringExtra("authCode");
- mAuthProvider = data.getStringExtra("authProvider");
- logMessage("authCode: " + mAuthCode);
- logMessage("authProvider: " + mAuthProvider);
-
- final Dialog dialog = new Dialog(context);
- dialog.setContentView(R.layout.dialog_entry);
- dialog.setTitle("SignUp Acccount IP Address");
- final EditText ip = (EditText) dialog
- .findViewById(R.id.EditTextEntry);
- if (RemoteAddress != null) {
- ip.setText(RemoteAddress);
- }
- Button dialogButton = (Button) dialog
- .findViewById(R.id.entryButtonOK);
- dialogButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- dialog.dismiss();
- RemoteAddress = ip.getText().toString();
- CIServer = CI_SERVER_PREFIX + RemoteAddress;
- logMessage("server address for signup is: \n" + CIServer);
- try {
- mAccountManager = OcPlatform
- .constructAccountManagerObject(CIServer, EnumSet
- .of(OcConnectivityType.CT_ADAPTER_TCP));
- logMessage("Calling signup API");
-
- if (mAuthProvider.equals("samsung")
- || mAuthProvider.equals("samsung-us")) {
- logMessage("Auth provider is samsung");
- Map<String, String> options = new HashMap<>();
- options.put("auth_server_url",
- "us-auth2.samsungosp.com");
- options.put("api_server_url",
- "us-auth2.samsungosp.com");
- mAccountManager.signUp(mAuthProvider, mAuthCode,
- options, onSignUp);
- } else {
- mAccountManager.signUp(mAuthProvider, mAuthCode,
- onSignUp);
- }
- } catch (OcException e) {
- e.printStackTrace();
- }
- }
- });
- dialog.show();
- }
- }
-
- OcResource.OnPostListener onRefreshTokenPost = new OcResource.OnPostListener() {
- @Override
- public void onPostCompleted(List<OcHeaderOption> list,
- OcRepresentation ocRepresentation) {
- logMessage("RefreshToken Completed.");
- try {
- mAccessToken = ocRepresentation.getValue("accesstoken");
- mRefreshtoken = ocRepresentation.getValue("refreshtoken");
- } catch (OcException e) {
- e.printStackTrace();
- }
- signIn();
- }
-
- @Override
- public void onPostFailed(Throwable throwable) {
- logMessage("RefreshToken failed.");
- Log.d(TAG, "onRefreshTokenPost failed..");
- }
- };
-
- public void refreshToken() {
-
- if (deviceID == null) {
- final Dialog dialog = new Dialog(context);
- dialog.setContentView(R.layout.dialog_entry);
- dialog.setTitle("Enter Device Id");
- dialog.setCanceledOnTouchOutside(false);
- final EditText id = (EditText) dialog
- .findViewById(R.id.EditTextEntry);
-
- Button dialogButton = (Button) dialog
- .findViewById(R.id.entryButtonOK);
- dialogButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- dialog.dismiss();
- deviceID = id.getText().toString();
- }
- });
- dialog.show();
- }
- try {
- OcResource authResource = OcPlatform.constructResourceObject(
- CIServer, "/.well-known/ocf/account/tokenrefresh",
- EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP,
- OcConnectivityType.CT_IP_USE_V4),
- false, Arrays.asList("oic.wk.account"),
- Arrays.asList(OcPlatform.DEFAULT_INTERFACE));
- OcRepresentation rep = new OcRepresentation();
-
- showToast("RefreshToken in progress..");
- logMessage("RefreshToken in progress..");
- rep.setValue("di", deviceID);
- rep.setValue("granttype", "refresh_token");
- rep.setValue("refreshtoken", mRefreshtoken);
- rep.setValue("uid", mUserID);
- authResource.post(rep, new HashMap<String, String>(),
- onRefreshTokenPost);
- } catch (OcException e) {
- e.printStackTrace();
- }
-
- Log.d(TAG, "No error while executing login");
- }
-}
+++ /dev/null
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:id="@+id/loginLayout"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical"
- tools:context=".LoginActivity">
-
- <WebView
- android:id="@+id/webView"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:visibility="visible" />
-
-</LinearLayout>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="utf-8"?>\r
-<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"\r
- xmlns:tools="http://schemas.android.com/tools"\r
- android:layout_width="match_parent"\r
- android:layout_height="match_parent"\r
- android:paddingBottom="@dimen/activity_vertical_margin"\r
- android:paddingLeft="@dimen/activity_horizontal_margin"\r
- android:paddingRight="@dimen/activity_horizontal_margin"\r
- android:paddingTop="@dimen/activity_vertical_margin"\r
- tools:context=".MainActivity">\r
-\r
- <ScrollView\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:fillViewport="true">\r
- <LinearLayout\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:paddingLeft="1dp"\r
- android:paddingRight="1dp"\r
- android:orientation="vertical" >\r
-\r
- <View\r
- android:layout_width="match_parent"\r
- android:layout_height="1dp"\r
- android:layout_alignParentBottom="true"\r
- android:background="@android:color/darker_gray"/>\r
-\r
- <LinearLayout\r
- android:layout_width="match_parent"\r
- android:layout_height="10dp">\r
- </LinearLayout>\r
-\r
- <LinearLayout\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:paddingLeft="5dp"\r
- android:paddingRight="5dp"\r
- android:orientation="vertical" >\r
-\r
- <LinearLayout\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:paddingLeft="5dp"\r
- android:paddingRight="5dp"\r
- android:orientation="horizontal" >\r
- <Button\r
- android:layout_gravity="center_vertical|center_horizontal"\r
- android:layout_height="60dp"\r
- android:layout_width="wrap_content"\r
- android:layout_weight="1"\r
- android:id="@+id/BtnStart"\r
- android:text="START"/>\r
- <Button\r
- android:layout_gravity="center_vertical|center_horizontal"\r
- android:layout_height="60dp"\r
- android:layout_width="wrap_content"\r
- android:layout_weight="1"\r
- android:id="@+id/BtnStop"\r
- android:text="STOP"/>\r
- </LinearLayout>\r
- </LinearLayout>\r
- <LinearLayout\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:paddingLeft="5dp"\r
- android:paddingRight="5dp"\r
- android:orientation="vertical" >\r
- <LinearLayout\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:paddingLeft="5dp"\r
- android:paddingRight="5dp"\r
- android:orientation="horizontal" >\r
- <Button\r
- android:layout_gravity="center_vertical|center_horizontal"\r
- android:layout_height="60dp"\r
- android:layout_width="wrap_content"\r
- android:layout_weight="1"\r
- android:id="@+id/BtnRescan"\r
- android:text="RESCAN"/>\r
- <Button\r
- android:layout_gravity="center_vertical|center_horizontal"\r
- android:layout_height="60dp"\r
- android:layout_width="wrap_content"\r
- android:layout_weight="1"\r
- android:id="@+id/BtnGetTopicList"\r
- android:text="Get TopicList"/>\r
- </LinearLayout>\r
- </LinearLayout>\r
- <LinearLayout\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:paddingLeft="5dp"\r
- android:paddingRight="5dp"\r
- android:orientation="horizontal"\r
- android:weightSum="1">\r
-\r
- <Button\r
- android:layout_height="wrap_content"\r
- android:layout_width="150dp"\r
- android:id="@+id/BtnSubscribe"\r
- android:text="Subscribe"/>\r
- <Button\r
- android:layout_height="wrap_content"\r
- android:layout_width="150dp"\r
- android:id="@+id/BtnUnsubscribe"\r
- android:text="Unsubscribe" />\r
- </LinearLayout>\r
- <LinearLayout\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:paddingLeft="5dp"\r
- android:paddingRight="5dp"\r
- android:orientation="horizontal"\r
- android:weightSum="1">\r
-\r
- <Button\r
- android:layout_height="wrap_content"\r
- android:layout_width="100dp"\r
- android:id="@+id/signup"\r
- android:text="Sign Up"/>\r
-\r
- <Button\r
- android:layout_height="wrap_content"\r
- android:layout_width="100dp"\r
- android:id="@+id/signin"\r
- android:text="Sign In" />\r
- <Button\r
- android:layout_height="wrap_content"\r
- android:layout_width="100dp"\r
- android:id="@+id/signout"\r
- android:text="Sign Out" />\r
- </LinearLayout>\r
- <LinearLayout\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:paddingLeft="5dp"\r
- android:paddingRight="5dp"\r
- android:orientation="horizontal"\r
- android:weightSum="1">\r
-\r
- <Button\r
- android:layout_height="wrap_content"\r
- android:layout_width="150dp"\r
- android:id="@+id/BtnEnableRemoteService"\r
- android:text="Enable Remote Service"/>\r
-\r
- <Button\r
- android:layout_height="wrap_content"\r
- android:layout_width="150dp"\r
- android:id="@+id/subscribeMQService"\r
- android:text="Subscribe MQ Service" />\r
- </LinearLayout>\r
- <LinearLayout\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:paddingLeft="5dp"\r
- android:paddingRight="5dp"\r
- android:orientation="vertical" >\r
- <LinearLayout\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:paddingLeft="5dp"\r
- android:paddingRight="5dp"\r
- android:orientation="vertical" >\r
- <Button\r
- android:layout_gravity="center_vertical|center_horizontal"\r
- android:layout_height="60dp"\r
- android:layout_width="match_parent"\r
- android:id="@+id/BtnUpdateTopicList"\r
- android:text="Update TopicList"/>\r
- </LinearLayout>\r
- </LinearLayout>\r
- <LinearLayout\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:paddingLeft="5dp"\r
- android:paddingRight="5dp"\r
- android:orientation="horizontal" >\r
-\r
- <Button\r
- android:layout_gravity="center_vertical|center_horizontal"\r
- android:layout_height="60dp"\r
- android:layout_width="match_parent"\r
- android:id="@+id/BtnClearLog"\r
- android:text="Clear Log"/>\r
- </LinearLayout>\r
-\r
- <ScrollView\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:fillViewport="true">\r
-\r
- <LinearLayout\r
- android:layout_width="match_parent"\r
- android:layout_height="1000dp"\r
- android:paddingLeft="5dp"\r
- android:paddingRight="5dp"\r
- android:orientation="horizontal" >\r
-\r
- <TextView\r
- android:layout_gravity="center_vertical|center_horizontal"\r
- android:layout_height="1000dp"\r
- android:layout_width="match_parent"\r
- android:scrollbars="vertical"\r
- android:id="@+id/TvLog"/>\r
- </LinearLayout>\r
-\r
- </ScrollView>\r
-\r
-\r
- <View\r
- android:layout_width="match_parent"\r
- android:layout_height="1dp"\r
- android:layout_alignParentBottom="true"\r
- android:background="@android:color/darker_gray"/>\r
-\r
- </LinearLayout>\r
- </ScrollView>\r
-</RelativeLayout>\r
+++ /dev/null
-<?xml version="1.0" encoding="utf-8"?>
-<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent" >
-
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:paddingLeft="1dp"
- android:paddingRight="1dp"
- android:orientation="vertical" >
-
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:paddingLeft="5dp"
- android:paddingRight="5dp"
- android:orientation="horizontal" >
-
- <Button
- android:layout_height="wrap_content"
- android:layout_width="wrap_content"
- android:id="@+id/BtnAuth"
- android:text="@string/btn_auth"
- android:onClick="selfDestruct" />
-
- <EditText
- android:id="@+id/EditTextAuth"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:windowSoftInputMode="stateHidden"
- android:hint="Add Auth Provider Name" />
- </LinearLayout>
-
- <LinearLayout
- android:id="@+id/LinearBody"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:paddingLeft="5dp"
- android:paddingRight="5dp"
- android:orientation="horizontal" >
-
- <Button
- android:layout_height="wrap_content"
- android:layout_width="wrap_content"
- android:id="@+id/BtnUrl"
- android:text="@string/btn_url"
- android:onClick="selfDestruct" />
-
- <EditText
- android:id="@+id/EditTextUrl"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:windowSoftInputMode="stateHidden"
- android:hint="Add Login Account URL" />
- </LinearLayout>
-
- <Button
- android:layout_gravity="center_vertical|center_horizontal"
- android:layout_height="wrap_content"
- android:layout_width="match_parent"
- android:id="@+id/dialogButtonOK"
- android:text="@string/btn_ok"
- />
- </LinearLayout>
-
-
-</RelativeLayout>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="utf-8"?>
-<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent" >
-
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:paddingLeft="1dp"
- android:paddingRight="1dp"
- android:orientation="vertical" >
-
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:paddingLeft="5dp"
- android:paddingRight="5dp"
- android:orientation="horizontal" >
-
- <EditText
- android:id="@+id/EditTextEntry"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:windowSoftInputMode="stateHidden"
- android:hint="Add Required Details" />
- </LinearLayout>
-
-
- <Button
- android:layout_gravity="center_vertical|center_horizontal"
- android:layout_height="wrap_content"
- android:layout_width="match_parent"
- android:id="@+id/entryButtonOK"
- android:text="@string/btn_ok"
- />
- </LinearLayout>
-
-
-</RelativeLayout>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="utf-8"?>
-<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent" >
-
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:paddingLeft="1dp"
- android:paddingRight="1dp"
- android:orientation="vertical" >
-
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:paddingLeft="5dp"
- android:paddingRight="5dp"
- android:orientation="horizontal" >
-
- <Button
- android:layout_height="wrap_content"
- android:layout_width="wrap_content"
- android:id="@+id/BtnAuth"
- android:text="@string/btn_addr"
- android:onClick="selfDestruct" />
-
- <EditText
- android:id="@+id/EditTextIp"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:windowSoftInputMode="stateHidden"
- android:hint="Add MQ Server IP Address" />
- </LinearLayout>
-
- <LinearLayout
- android:id="@+id/LinearBody"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:paddingLeft="5dp"
- android:paddingRight="5dp"
- android:orientation="horizontal" >
-
- <Button
- android:layout_height="wrap_content"
- android:layout_width="wrap_content"
- android:id="@+id/BtnTopic"
- android:text="@string/btn_topic"
- android:onClick="selfDestruct" />
-
- <EditText
- android:id="@+id/EditTextMqTopic"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:windowSoftInputMode="stateHidden"
- android:hint="Add MQ Topic name" />
- </LinearLayout>
-
- <Button
- android:layout_gravity="center_vertical|center_horizontal"
- android:layout_height="wrap_content"
- android:layout_width="match_parent"
- android:id="@+id/mqButtonOK"
- android:text="@string/btn_ok"
- />
- </LinearLayout>
-
-
-</RelativeLayout>
\ No newline at end of file
+++ /dev/null
-<resources>\r
- <!-- Example customization of dimensions originally defined in res/values/dimens.xml\r
- (such as screen margins) for screens with more than 820dp of available width. This\r
- would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively). -->\r
- <dimen name="activity_horizontal_margin">64dp</dimen>\r
-</resources>\r
+++ /dev/null
-<?xml version="1.0" encoding="utf-8"?>\r
-<resources>\r
- <color name="colorPrimary">#3F51B5</color>\r
- <color name="colorPrimaryDark">#303F9F</color>\r
- <color name="colorAccent">#FF4081</color>\r
-</resources>\r
+++ /dev/null
-<resources>\r
- <!-- Default screen margins, per the Android Design guidelines. -->\r
- <dimen name="activity_horizontal_margin">16dp</dimen>\r
- <dimen name="activity_vertical_margin">16dp</dimen>\r
-</resources>\r
+++ /dev/null
-<resources>\r
- <string name="app_name">NotificationConsumerExample</string>\r
- <string name="btn_auth">Auth</string>\r
- <string name="btn_url"> URL</string>\r
- <string name="btn_ok">Enter Details</string>\r
- <string name="btn_addr"> Addr. </string>\r
- <string name="btn_topic">Topic</string>\r
-</resources>\r
+++ /dev/null
-<resources>\r
-\r
- <!--\r
- Base application theme, dependent on API level. This theme is replaced\r
- by AppBaseTheme from res/values-vXX/styles.xml on newer devices.\r
- -->\r
- <style name="AppBaseTheme" parent="android:Theme.Light">\r
- <!--\r
- Theme customizations available in newer API levels can go in\r
- res/values-vXX/styles.xml, while customizations related to\r
- backward-compatibility can go here.\r
- -->\r
- </style>\r
-\r
- <!-- Application theme. -->\r
- <style name="AppTheme" parent="AppBaseTheme">\r
- <!-- All customizations that are NOT specific to a particular API-level can go here. -->\r
- </style>\r
-\r
-</resources>
\ No newline at end of file
+++ /dev/null
-// Top-level build file where you can add configuration options common to all sub-projects/modules.
-
-buildscript {
- repositories {
- jcenter()
- }
- dependencies {
- classpath 'com.android.tools.build:gradle:1.3.0'
-
- // NOTE: Do not place your application dependencies here; they belong
- // in the individual module build.gradle files
- }
-}
-
-allprojects {
- repositories {
- jcenter()
-
- flatDir {
- dirs '../../../../android/notification-service/build/outputs/aar'
- dirs '../../../../../../android/android_api/base/build/outputs/aar'
- }
- }
-}
-
-task clean(type: Delete) {
- delete rootProject.buildDir
-}
+++ /dev/null
-@if "%DEBUG%" == "" @echo off\r
-@rem ##########################################################################\r
-@rem\r
-@rem Gradle startup script for Windows\r
-@rem\r
-@rem ##########################################################################\r
-\r
-@rem Set local scope for the variables with windows NT shell\r
-if "%OS%"=="Windows_NT" setlocal\r
-\r
-@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.\r
-set DEFAULT_JVM_OPTS=\r
-\r
-set DIRNAME=%~dp0\r
-if "%DIRNAME%" == "" set DIRNAME=.\r
-set APP_BASE_NAME=%~n0\r
-set APP_HOME=%DIRNAME%\r
-\r
-@rem Find java.exe\r
-if defined JAVA_HOME goto findJavaFromJavaHome\r
-\r
-set JAVA_EXE=java.exe\r
-%JAVA_EXE% -version >NUL 2>&1\r
-if "%ERRORLEVEL%" == "0" goto init\r
-\r
-echo.\r
-echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.\r
-echo.\r
-echo Please set the JAVA_HOME variable in your environment to match the\r
-echo location of your Java installation.\r
-\r
-goto fail\r
-\r
-:findJavaFromJavaHome\r
-set JAVA_HOME=%JAVA_HOME:"=%\r
-set JAVA_EXE=%JAVA_HOME%/bin/java.exe\r
-\r
-if exist "%JAVA_EXE%" goto init\r
-\r
-echo.\r
-echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%\r
-echo.\r
-echo Please set the JAVA_HOME variable in your environment to match the\r
-echo location of your Java installation.\r
-\r
-goto fail\r
-\r
-:init\r
-@rem Get command-line arguments, handling Windowz variants\r
-\r
-if not "%OS%" == "Windows_NT" goto win9xME_args\r
-if "%@eval[2+2]" == "4" goto 4NT_args\r
-\r
-:win9xME_args\r
-@rem Slurp the command line arguments.\r
-set CMD_LINE_ARGS=\r
-set _SKIP=2\r
-\r
-:win9xME_args_slurp\r
-if "x%~1" == "x" goto execute\r
-\r
-set CMD_LINE_ARGS=%*\r
-goto execute\r
-\r
-:4NT_args\r
-@rem Get arguments from the 4NT Shell from JP Software\r
-set CMD_LINE_ARGS=%$\r
-\r
-:execute\r
-@rem Setup the command line\r
-\r
-set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar\r
-\r
-@rem Execute Gradle\r
-"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%\r
-\r
-:end\r
-@rem End local scope for the variables with windows NT shell\r
-if "%ERRORLEVEL%"=="0" goto mainEnd\r
-\r
-:fail\r
-rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of\r
-rem the _cmd.exe /c_ return code!\r
-if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1\r
-exit /b 1\r
-\r
-:mainEnd\r
-if "%OS%"=="Windows_NT" endlocal\r
-\r
-:omega\r
+++ /dev/null
-include ':app'
\ No newline at end of file
+++ /dev/null
-*.iml\r
-.gradle\r
-/local.properties\r
-/.idea/workspace.xml\r
-/.idea/libraries\r
-.DS_Store\r
-/build\r
-/captures\r
+++ /dev/null
-#//******************************************************************
-#//
-#// Copyright 2016 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.
-#//
-#//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-import os
-import platform
-Import('env')
-
-android_home = env.get('ANDROID_HOME')
-
-ANDROID_TARGET_ARCH = env.get('TARGET_ARCH')
-if env.get('RELEASE'):
- ANDROID_RELEASE="release"
-else:
- ANDROID_RELEASE="debug"
-
-os.environ['ANDROID_HOME'] = env.get('ANDROID_HOME')
-os.environ['ANDROID_NDK_HOME'] = env.get('ANDROID_NDK')
-
-if not os.path.exists(android_home + '/platforms/android-21') or not os.path.exists(android_home + '/build-tools/20.0.0'):
- print '''
-***************************************** Info ********************************
-* Either 'Android API 21' is not installed or 'Android SDK Build Tools *
-* 20.0.0' is not installed. The Android SDK Manager will now open. Please *
-* be sure to deselect all options, then select the following 2 packages: *
-* 1. Under "Tools" select "Android SDK Build-tools" Revision 20. *
-* 2. Under "Android 5.0.1 (API 21)" select "SDK Platform" *
-* 3. Continue by selecting "Install 2 Packages" *
-* *
-* NOTE: If you have an http proxy, please press ctrl+c now and edit/create *
-* the following file in your $HOME directory as follows: *
-* *
-* Edit/Create file: "$HOME/.android/androidtool.cfg" *
-* *
-* http.proxyPort=<YOUR_PORT_NUMBER> *
-* sdkman.monitor.density=108 *
-* http.proxyHost=<YOUR_HTTP_PROXY_ADDRESS> *
-* sdkman.show.update.only=true *
-* sdkman.ask.adb.restart=false *
-* sdkman.force.http=true *
-* sdkman.show.updateonly=true *
-* *
-*******************************************************************************
-
-...Opening Android SDK Manager now. Once you are finished, the build will continue.
-'''
- os.system(android_home + '/tools/android')
-
-def ensure_libs(target, source, env):
- return target, [source,
- env.get('BUILD_DIR') + 'libnotification_provider_jni.so',
- env.get('BUILD_DIR') + 'libnotification_provider_wrapper.so',
- env.get('BUILD_DIR') + 'libnotification_provider.so',
- env.get('BUILD_DIR') + 'libnotification_consumer_jni.so',
- env.get('BUILD_DIR') + 'libnotification_consumer_wrapper.so',
- env.get('BUILD_DIR') + 'libnotification_consumer.so']
-
-jdk_env = Environment(ENV=os.environ)
-jdk_env['BUILDERS']['Gradle'] = Builder(action = env.get('ANDROID_GRADLE') +
- ' build -bservice/notification/examples/android/NotiProviderExample/build.gradle -PTARGET_ARCH=%s -PRELEASE=%s --stacktrace' %(ANDROID_TARGET_ARCH, ANDROID_RELEASE),
- emitter = ensure_libs)
-jdk_env['BUILD_DIR'] = env.get('BUILD_DIR')
-cmdBuildNotificationProviderApp=jdk_env.Gradle(target="app/apk",
- source=["app/src/main/java/org/iotivity/service/ns/sample/provider/MainActivity.java",
- "app/src/main/java/org/iotivity/service/ns/sample/provider/NotiListener.java",
- "app/src/main/java/org/iotivity/service/ns/sample/provider/ProviderSample.java"])
-jdk_env.Clean(cmdBuildNotificationProviderApp, '#/service/notification/examples/android/NotiProviderExample/build')
-Depends(cmdBuildNotificationProviderApp, env.get('notificationAAR'))
+++ /dev/null
-apply plugin: 'com.android.application'
-
-android {
- compileSdkVersion 21
- buildToolsVersion "20.0.0"
-
- packagingOptions {
- pickFirst 'lib/armeabi/libocstack-jni.so'
- pickFirst 'lib/armeabi-v7a/libocstack-jni.so'
- pickFirst 'lib/x86/libocstack-jni.so'
- pickFirst 'lib/x86_64/libocstack-jni.so'
- pickFirst 'lib/arm64-v8a/libocstack-jni.so'
- pickFirst 'lib/armeabi/libresource_directory.so'
- pickFirst 'lib/armeabi-v7a/libresource_directory.so'
- pickFirst 'lib/x86/libresource_directory.so'
- pickFirst 'lib/x86_64/libresource_directory.so'
- pickFirst 'lib/arm64-v8a/libresource_directory.so'
- }
-
- defaultConfig {
- applicationId "sample.notification.service.iotivity.org.notificationprovidersample"
- minSdkVersion 21
- targetSdkVersion 21
- versionCode 1
- versionName "1.0"
- }
-
- lintOptions {
- abortOnError false
- }
-}
-
-dependencies {
- compile fileTree(include: ['*.jar'], dir: 'libs')
- compile ":iotivity-base-${TARGET_ARCH}-${RELEASE}@aar"
- compile ":iotivity-${TARGET_ARCH}-notification-service-${RELEASE}@aar"
-}
+++ /dev/null
-# Add project specific ProGuard rules here.\r
-# By default, the flags in this file are appended to flags specified\r
-# in D:\adt-bundle-windows-x86_64-20140321\sdk/tools/proguard/proguard-android.txt\r
-# You can edit the include path and order by changing the proguardFiles\r
-# directive in build.gradle.\r
-#\r
-# For more details, see\r
-# http://developer.android.com/guide/developing/tools/proguard.html\r
-\r
-# Add any project specific keep options here:\r
-\r
-# If your project uses WebView with JS, uncomment the following\r
-# and specify the fully qualified class name to the JavaScript interface\r
-# class:\r
-#-keepclassmembers class fqcn.of.javascript.interface.for.webview {\r
-# public *;\r
-#}\r
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2016 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.iotivity.service.ns.sample.provider;
-
-import android.util.Log;
-
-import org.iotivity.service.ns.common.Message;
-import org.iotivity.service.ns.common.SyncInfo;
-import org.iotivity.service.ns.consumer.ConsumerService;
-import org.iotivity.service.ns.consumer.Provider;
-
-import java.util.concurrent.CountDownLatch;
-
-class ConsumerSimulator implements ConsumerService.OnProviderDiscoveredListener,
- Provider.OnProviderStateListener, Provider.OnMessageReceivedListener,
- Provider.OnSyncInfoReceivedListener {
- private String TAG = "Consumer Simulator";
- private Provider mProvider;
- private CountDownLatch mLockObject;
- private Response mResponse;
- private String mExpectCb;
-
- public void set(CountDownLatch lockObject, Response response, String name) {
- Log.i(TAG, "Setting lock Simulator: ");
- mLockObject = lockObject;
- mResponse = response;
- mExpectCb = name;
- }
-
- @Override
- public void onProviderDiscovered(Provider provider) {
- mProvider = provider;
- try {
- provider.setListener(this, this, this);
- if (!provider.isSubscribed()) {
- provider.subscribe();
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
-
- }
-
- @Override
- public void onProviderStateReceived(Provider.ProviderState providerState) {
- }
-
- @Override
- public void onMessageReceived(Message message) {
- if (mExpectCb == "msg") {
- mResponse.set(true);
- mLockObject.countDown();
- }
- }
-
- @Override
- public void onSyncInfoReceived(SyncInfo syncInfo) {
- if (mExpectCb == "sync") {
- mResponse.set(true);
- mLockObject.countDown();
- }
- }
-
- public void sendSyncInfo(long id, SyncInfo.SyncType type) {
- try {
- mProvider.sendSyncInfo(id, type);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-/*
-* Copyright 2016 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.iotivity.service.ns.sample.provider;
-
-import java.util.Iterator;
-import java.util.Vector;
-import java.util.concurrent.CountDownLatch;
-
-import android.app.Application;
-import android.content.Context;
-import android.test.ApplicationTestCase;
-import android.util.Log;
-
-import org.iotivity.base.ModeType;
-import org.iotivity.base.OcPlatform;
-import org.iotivity.base.PlatformConfig;
-import org.iotivity.base.QualityOfService;
-import org.iotivity.base.ServiceType;
-import org.iotivity.service.ns.common.NSException;
-import org.iotivity.service.ns.common.NSErrorCode;
-import org.iotivity.service.ns.common.SyncInfo;
-import org.iotivity.service.ns.common.Topic;
-
-import android.support.test.runner.AndroidJUnit4;
-
-import org.iotivity.service.ns.consumer.ConsumerService;
-import org.iotivity.service.ns.provider.Consumer;
-import org.iotivity.service.ns.provider.ProviderService;
-import org.junit.After;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.junit.Before;
-import org.junit.runner.RunWith;
-
-import java.util.concurrent.TimeUnit;
-
-/**
- * To work on unit tests, switch the Test Artifact in the Build Variants view.
- */
-@RunWith(AndroidJUnit4.class)
-public class ExampleUnitTest extends ApplicationTestCase<Application> {
- public ExampleUnitTest() {
- super(Application.class);
- }
-
- private static Context mContext = null;
- private static SubscriptionCallbackListener subCb;
- private static SyncCallbackListener syncCb;
- private CountDownLatch lockObject;
- private Response response;
- private static ProviderService gProviderRes;
- private static ConsumerService gConsumerRes;
- private static ConsumerSimulator gConsumerSim;
- private static String TAG = "UnitTest ProviderService";
-
- public void start(boolean subControllability) {
- try {
- gProviderRes.start(subCb, syncCb, subControllability, "ok", false);
- gConsumerRes.start(gConsumerSim);
- lockObject.await(4000, TimeUnit.MILLISECONDS);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- public org.iotivity.service.ns.common.Message createMessage() {
- org.iotivity.service.ns.common.Message msg = null;
- try {
- msg = gProviderRes.createMessage();
- msg.setTitle("Title");
- msg.setSourceName("Source");
- msg.setContentText("ContentText");
- } catch (Exception e) {
- e.printStackTrace();
- }
- return msg;
- }
-
- public org.iotivity.service.ns.common.Message sendMessage(
- boolean accepted) {
- lockObject = new CountDownLatch(1);
- response = new Response();
- org.iotivity.service.ns.common.Message msg = null;
- gConsumerSim.set(lockObject, response, "msg");
- try {
- subCb.get().acceptSubscription(accepted);
- CountDownLatch waitLock = new CountDownLatch(1);
- waitLock.await(400, TimeUnit.MILLISECONDS);
- msg = createMessage();
- gProviderRes.sendMessage(msg);
- lockObject.await(4000, TimeUnit.MILLISECONDS);
- } catch (Exception e) {
- e.printStackTrace();
- }
- return msg;
- }
-
- @BeforeClass
- public static void Initialize() {
- PlatformConfig platformConfig = new PlatformConfig(mContext,
- ServiceType.IN_PROC, ModeType.CLIENT_SERVER, "0.0.0.0",
- 0, // Uses randomly available port
- QualityOfService.LOW);
-
- OcPlatform.Configure(platformConfig);
- try {
- OcPlatform.stopPresence(); // Initialize OcPlatform
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- @Before
- public void SetUp() {
- Log.i(TAG, "SetUp - IN");
- subCb = new SubscriptionCallbackListener();
- syncCb = new SyncCallbackListener();
- gConsumerRes = ConsumerService.getInstance();
- gProviderRes = ProviderService.getInstance();
- gConsumerSim = new ConsumerSimulator();
- lockObject = new CountDownLatch(1);
- response = new Response();
- subCb.set(lockObject, response);
- Log.i(TAG, "SetUp - OUT");
- }
-
- @After
- public void TearDown() {
- Log.i(TAG, "TearDown - IN");
- try {
- gProviderRes.stop();
- gConsumerRes.stop();
- lockObject = new CountDownLatch(1);
- lockObject.await(2000, TimeUnit.MILLISECONDS);
- } catch (Exception e) {
- e.printStackTrace();
- }
- Log.i(TAG, "TearDown - OUT");
- }
-
- @Test
- public void StartProviderPositiveWithPolicyTrue() {
- try {
- gProviderRes.start(subCb, syncCb, true, "ok", false);
- gProviderRes.stop();
- } catch (NSException e) {
- e.printStackTrace();
- assertEquals(NSErrorCode.OK, e.getErrorCode());
- }
- }
-
- @Test
- public void StartProviderPositiveWithPolicyFalse() {
- try {
- gProviderRes.start(subCb, syncCb, false, "ok", false);
- gProviderRes.stop();
- } catch (NSException e) {
- e.printStackTrace();
- assertEquals(NSErrorCode.OK, e.getErrorCode());
- }
- }
-
- @Test
- public void StopProviderPositive() {
- try {
- gProviderRes.start(subCb, syncCb, true, "ok", false);
- gProviderRes.stop();
- } catch (NSException e) {
- e.printStackTrace();
- assertEquals(NSErrorCode.OK, e.getErrorCode());
- }
- }
-
- @Test
- public void ExpectCallbackWhenReceiveSubscribeRequestWithAccepterProvider() {
- start(true);
- assertEquals(true, response.get());
- }
-
- @Test
- public void NeverCallNotifyOnConsumerByAcceptIsFalse() {
- start(true);
- assertEquals(true, response.get());
- sendMessage(false);
- assertEquals(false, response.get());
- }
-
- @Test
- public void ExpectCallNotifyOnConsumerByAcceptIsTrue() {
-
- start(true);
- assertEquals(true, response.get());
- sendMessage(true);
- assertEquals(true, response.get());
- }
-
- @Test
- public void ExpectCallbackSyncOnReadToConsumer() {
- start(true);
- assertEquals(true, response.get());
- org.iotivity.service.ns.common.Message msg = sendMessage(true);
- assertEquals(true, response.get());
- try {
- lockObject = new CountDownLatch(1);
- response = new Response();
- gConsumerSim.set(lockObject, response, "sync");
- gProviderRes.sendSyncInfo(msg.getMessageId(),
- SyncInfo.SyncType.READ);
- lockObject.await(4000, TimeUnit.MILLISECONDS);
- } catch (Exception e) {
- e.printStackTrace();
- }
- assertEquals(true, response.get());
- }
-
- @Test
- public void ExpectCallbackSyncOnReadFromConsumer() {
-
- start(true);
- assertEquals(true, response.get());
- org.iotivity.service.ns.common.Message msg = sendMessage(true);
- assertEquals(true, response.get());
- try {
- lockObject = new CountDownLatch(1);
- response = new Response();
- syncCb.set(lockObject, response);
- gConsumerSim.sendSyncInfo(msg.getMessageId(),
- SyncInfo.SyncType.READ);
- lockObject.await(4000, TimeUnit.MILLISECONDS);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- @Test
- public void ExpectEqualAddedTopicsAndRegisteredTopics() {
- boolean isSame = true;
- String str[] = { "TOPIC1", "TOPIC2" };
- try {
- gProviderRes.start(subCb, syncCb, true, "ok", false);
- gProviderRes.registerTopic(str[0]);
- gProviderRes.registerTopic(str[1]);
- Vector<Topic> list = gProviderRes.getRegisteredTopicList()
- .getTopicsList();
- Iterator<Topic> it = list.iterator();
- if (list.size() != 2) {
- isSame = false;
- Log.i(TAG, "Size is " + list.size());
- }
- int count = 0;
- while (it.hasNext()) {
- Topic element = it.next();
- Log.i(TAG, "element is " + element.getTopicName());
- if (!str[count].equals(element.getTopicName())) {
- isSame = false;
- }
- count++;
- }
-
- } catch (Exception e) {
- e.printStackTrace();
- }
- assertEquals(true, isSame);
- }
-
- @Test
- public void ExpectEqualUnregisteredTopicsAndRegisteredTopics() {
- boolean isSame = true;
- String str[] = { "TOPIC1", "TOPIC2" };
- try {
- gProviderRes.start(subCb, syncCb, true, "ok", false);
- gProviderRes.registerTopic(str[0]);
- gProviderRes.registerTopic(str[1]);
- gProviderRes.unregisterTopic(str[0]);
- Vector<Topic> list = gProviderRes.getRegisteredTopicList()
- .getTopicsList();
- Iterator<Topic> it = list.iterator();
- if (list.size() != 1) {
- isSame = false;
- Log.i(TAG, "Size is " + list.size());
- }
- int count = 1;
- while (it.hasNext()) {
- Topic element = it.next();
- Log.i(TAG, "element is " + element.getTopicName());
- if (!str[count].equals(element.getTopicName())) {
- isSame = false;
- }
- }
-
- } catch (Exception e) {
- e.printStackTrace();
- }
- assertEquals(true, isSame);
- }
-
- @Test
- public void ExpectEqualSetConsumerTopicsAndGetConsumerTopics() {
- boolean isSame = false;
- start(true);
- assertEquals(true, response.get());
- String str[] = { "TOPIC1", "TOPIC2" };
- try {
- gProviderRes.registerTopic(str[0]);
- gProviderRes.registerTopic(str[1]);
- subCb.get().setTopic(str[0]);
-
- Vector<Topic> list = subCb.get().getConsumerTopicList()
- .getTopicsList();
- Iterator<Topic> it = list.iterator();
- int count = 0;
- String[] compStr = new String[10];
- Topic.TopicState[] state = new Topic.TopicState[10];
- while (it.hasNext()) {
- Topic element = it.next();
- Log.i(TAG, "element is " + element.getTopicName());
- compStr[count] = element.getTopicName();
- state[count++] = element.getState();
- }
- if (compStr[0].compareTo(str[0]) == 0
- && compStr[1].compareTo(str[1]) == 0
- && state[0] == Topic.TopicState.SUBSCRIBED
- && state[1] == Topic.TopicState.UNSUBSCRIBED) {
- isSame = true;
- }
-
- } catch (Exception e) {
- e.printStackTrace();
- }
- assertEquals(true, isSame);
- }
-
- @Test
- public void ExpectEqualUnSetConsumerTopicsAndGetConsumerTopics() {
- boolean isSame = false;
- start(true);
- assertEquals(true, response.get());
- String str[] = { "TOPIC1", "TOPIC2" };
- try {
- gProviderRes.registerTopic(str[0]);
- gProviderRes.registerTopic(str[1]);
- subCb.get().setTopic(str[0]);
- subCb.get().setTopic(str[1]);
- subCb.get().unsetTopic(str[0]);
-
- Vector<Topic> list = subCb.get().getConsumerTopicList()
- .getTopicsList();
- Iterator<Topic> it = list.iterator();
- int count = 0;
- String[] compStr = new String[10];
- Topic.TopicState[] state = new Topic.TopicState[10];
- while (it.hasNext()) {
- Topic element = it.next();
- Log.i(TAG, "element is " + element.getTopicName());
- compStr[count] = element.getTopicName();
- state[count++] = element.getState();
- }
- if (compStr[0].compareTo(str[0]) == 0
- && compStr[1].compareTo(str[1]) == 0
- && state[0] == Topic.TopicState.UNSUBSCRIBED
- && state[1] == Topic.TopicState.SUBSCRIBED) {
- isSame = true;
- }
-
- } catch (Exception e) {
- e.printStackTrace();
- }
- assertEquals(true, isSame);
- }
-
-}
-
-class SubscriptionCallbackListener
- implements ProviderService.OnConsumerSubscribedListener {
- private CountDownLatch mLockObject;
- private Response mResponse;
- private Consumer mConsumer;
- private static String TAG = "UnitTest SubscriptionCallbackListener";
-
- @Override
- public void onConsumerSubscribed(Consumer consumer) {
- Log.i(TAG, "onConsumerSubscribed");
- mConsumer = consumer;
- if (mResponse != null) {
- mResponse.set(true);
- mLockObject.countDown();
- }
- }
-
- public void set(CountDownLatch lockObject, Response response) {
- mLockObject = lockObject;
- mResponse = response;
- }
-
- public Consumer get() {
- return mConsumer;
- }
-}
-
-class SyncCallbackListener
- implements ProviderService.OnMessageSynchronizedListener {
- private CountDownLatch mLockObject;
- private Response mResponse;
- private static String TAG = "UnitTest SyncCallbackListener";
-
- @Override
- public void onMessageSynchronized(SyncInfo syncInfo) {
- Log.i(TAG, "onMessageSynchronized");
- if (mResponse != null) {
- mResponse.set(true);
- mLockObject.countDown();
- }
- }
-
- public void set(CountDownLatch lockObject, Response response) {
- mLockObject = lockObject;
- mResponse = response;
- }
-}
-
-class Response {
- private boolean state;
-
- Response() {
- state = false;
- }
-
- public void set(boolean val) {
- state = val;
- }
-
- public boolean get() {
- return state;
- }
-}
+++ /dev/null
-<?xml version="1.0" encoding="utf-8"?>\r
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"\r
- package="org.iotivity.service.ns.sample.provider">\r
-\r
- <uses-feature android:name="android.hardware.nfc" />\r
- <uses-permission android:name="android.permission.READ_PHONE_STATE" />\r
- <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />\r
- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />\r
- <uses-permission android:name="android.permission.BLUETOOTH"/>\r
- <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>\r
- <uses-permission android:name="android.permission.INTERNET"/>\r
- <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>\r
- <uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE"/>\r
- <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>\r
- <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>\r
- <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>\r
- <uses-permission android:name="android.permission.NFC" />\r
-\r
- <application\r
- android:allowBackup="true"\r
- android:icon="@mipmap/ic_launcher"\r
- android:label="@string/app_name"\r
- android:supportsRtl="true"\r
- android:theme="@style/AppTheme">\r
- <activity android:name=".MainActivity">\r
- <intent-filter>\r
- <action android:name="android.intent.action.MAIN" />\r
-\r
- <category android:name="android.intent.category.LAUNCHER" />\r
- </intent-filter>\r
- </activity>\r
- <activity android:name=".LoginActivity" />\r
- <service\r
- android:name=".NotiListener"\r
- android:label="@string/app_name"\r
- android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">\r
-\r
- <intent-filter>\r
- <action android:name="android.service.notification.NotificationListenerService" />\r
- <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />\r
- </intent-filter>\r
- </service>\r
- </application>\r
-\r
-</manifest>\r
+++ /dev/null
-/*
- * ******************************************************************
- *
- * Copyright 2016 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.iotivity.service.ns.sample.provider;
-
-import android.app.Activity;
-import android.app.Dialog;
-import android.content.Context;
-import android.content.Intent;
-import android.net.UrlQuerySanitizer;
-import android.os.Bundle;
-import android.util.Log;
-import android.view.View;
-import android.webkit.WebView;
-import android.webkit.WebViewClient;
-import android.widget.Button;
-import android.widget.EditText;
-
-/**
- * This class is for login to the provider. Can be get auth code via web page.
- */
-public class LoginActivity extends Activity {
- private static final String TAG = "OIC_SIMPLE_LOGIN";
-
- private final Context context = this;
- private WebView mWebView = null;
- private static String loginAccount = null;
- private static String mAuthProvider = null;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_login);
-
- final Dialog dialog = new Dialog(context);
- dialog.setContentView(R.layout.dialog_auth);
- dialog.setTitle("Login Details");
- final EditText auth = (EditText) dialog.findViewById(R.id.EditTextAuth);
- final EditText url = (EditText) dialog.findViewById(R.id.EditTextUrl);
- if (loginAccount != null && mAuthProvider != null) {
- url.setText(loginAccount);
- auth.setText(mAuthProvider);
- }
-
- Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
- dialog.setCanceledOnTouchOutside(false);
- dialogButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- dialog.dismiss();
- loginAccount = url.getText().toString();
- mAuthProvider = auth.getText().toString();
-
- mWebView = (WebView) findViewById(R.id.webView);
- mWebView.setInitialScale(200);
- mWebView.getSettings().setJavaScriptEnabled(true);
- mWebView.getSettings().setBuiltInZoomControls(true);
- mWebView.setWebViewClient(new WebViewClientClass());
-
- mWebView.loadUrl(loginAccount);
- }
- });
- dialog.show();
- }
-
- public void onDestroy() {
- super.onDestroy();
- }
-
- private class WebViewClientClass extends WebViewClient {
-
- @Override
- public void onPageFinished(WebView view, String url) {
- Log.i(TAG,
- "onPageFinished!!! Response received: called url=" + url);
-
- if (url.contains("code") && url.contains("code_expires_in")) {
-
- mWebView.setVisibility(View.INVISIBLE);
-
- // parsing url
- UrlQuerySanitizer sanitizer = new UrlQuerySanitizer();
- sanitizer.setAllowUnregisteredParamaters(true);
- sanitizer.parseUrl(url);
-
- String mAuthCode = sanitizer.getValue("code");
- Log.i(TAG, "onPageFinished!!! authCode=" + mAuthCode);
-
- Intent intent = getIntent();
- intent.putExtra("authCode", mAuthCode);
- intent.putExtra("authProvider", mAuthProvider);
- setResult(RESULT_OK, intent);
-
- finish();
- }
- }
- }
-}
+++ /dev/null
-/*
-//******************************************************************
-//
-// Copyright 2016 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.iotivity.service.ns.sample.provider;
-
-import android.app.Dialog;
-import android.app.Notification;
-import android.app.NotificationManager;
-import android.content.Context;
-import android.content.Intent;
-import android.os.Bundle;
-import android.os.Handler;
-import android.os.Message;
-import android.util.Log;
-import android.view.View;
-import android.widget.Button;
-import android.widget.EditText;
-import android.widget.RadioButton;
-import android.widget.TextView;
-import android.widget.Toast;
-import android.app.Activity;
-
-import org.iotivity.base.ErrorCode;
-import org.iotivity.base.OcAccountManager;
-import org.iotivity.base.OcConnectivityType;
-import org.iotivity.base.OcException;
-import org.iotivity.base.OcHeaderOption;
-import org.iotivity.base.OcPlatform;
-import org.iotivity.base.OcRepresentation;
-import org.iotivity.base.OcResource;
-
-import java.util.Arrays;
-import java.util.EnumSet;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-public class MainActivity extends Activity
- implements OcAccountManager.OnPostListener {
-
- private final String TAG = "NS_MAIN_ACTIVITY";
- private static final int CONSUMER_SUBSCRIBED = 1;
- private static final int MESSAGE_SYNC = 2;
- private final int REQUEST_LOGIN = 1;
- private static final String CI_SERVER_PREFIX = "coap+tcp://";
- private final Context context = this;
-
- public static String deviceID = null;
- public static String CIServer = null;
- public static String RemoteAddress = null;
- public static String MQCloudAddress = null;
- public static String MQCloudTopic = null;
-
- private Button btnTitle;
- private Button btnBody;
- private Button btnTopic;
- private Button btnSend;
- private Button btnStart;
- private Button btnRegister;
- private Button btnSet;
- private Button btnStop;
- private Button btnLog;
- private Button signUp, signIn, signOut;
- private Button remoteService, subscribeMQ;
- private EditText editTextTitle;
- private EditText editTextBody;
- private EditText editTextTopic;
- private RadioButton radioProvider;
- private RadioButton radioConsumer;
- private static TextView TvLog;
-
- private OcAccountManager mAccountManager;
- String mAuthCode;
- String mAuthProvider;
- String mRefreshtoken;
- String mUserID;
- String mAccessToken;
-
- private static int notiId = 100;
- private boolean isStarted = false;
- private boolean gAcceptor = true;
- private boolean gRemoteService = true;
-
- private NotiListener mNotiListener = null;
- private ProviderSample mProviderSample = null;
-
- public static Handler mHandler = new Handler() {
- @Override
- public void handleMessage(Message msg) {
- switch (msg.what) {
- case CONSUMER_SUBSCRIBED:
- String ConsumerId = (String) msg.obj;
- if (ConsumerId != null)
- TvLog.append("Consumer Subscibed: " + ConsumerId + "\n");
- break;
-
- case MESSAGE_SYNC:
- String sync = (String) msg.obj;
- if (sync != null)
- TvLog.append("SyncInfo Received :" + sync + "\n");
- break;
-
- default:
- break;
- }
- }
-
- };
-
- public void showToast(final String toast) {
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- Toast.makeText(getApplicationContext(), toast,
- Toast.LENGTH_SHORT).show();
- }
- });
- }
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
-
- btnTitle = (Button) findViewById(R.id.BtnTitle);
- btnBody = (Button) findViewById(R.id.BtnBody);
- btnTopic = (Button) findViewById(R.id.BtnTopic);
- btnSend = (Button) findViewById(R.id.BtnCreateNoti);
-
- btnStart = (Button) findViewById(R.id.BtnStart);
- btnRegister = (Button) findViewById(R.id.BtnRegister);
- btnSet = (Button) findViewById(R.id.BtnSet);
- btnLog = (Button) findViewById(R.id.BtnLog);
- btnStop = (Button) findViewById(R.id.BtnStop);
-
- signUp = (Button) findViewById(R.id.signup);
- signIn = (Button) findViewById(R.id.signin);
- signOut = (Button) findViewById(R.id.signout);
- remoteService = (Button) findViewById(R.id.remoteService);
- subscribeMQ = (Button) findViewById(R.id.subscribeMQService);
-
- editTextTitle = (EditText) findViewById(R.id.EditTextTitle);
- editTextBody = (EditText) findViewById(R.id.EditTextBody);
- editTextTopic = (EditText) findViewById(R.id.EditTextTopic);
-
- radioProvider = (RadioButton) findViewById(R.id.RadioProvider);
- radioConsumer = (RadioButton) findViewById(R.id.RadioConsumer);
-
- TvLog = (TextView) findViewById(R.id.TvLog);
-
- btnTitle.setEnabled(false);
- btnBody.setEnabled(false);
- btnTopic.setEnabled(false);
-
- signIn.setEnabled(false);
- signOut.setEnabled(false);
- remoteService.setEnabled(false);
-
- btnSend.setOnClickListener(mClickListener);
- btnStart.setOnClickListener(mClickListener);
- btnRegister.setOnClickListener(mClickListener);
- btnSet.setOnClickListener(mClickListener);
- btnLog.setOnClickListener(mClickListener);
- btnStop.setOnClickListener(mClickListener);
- radioProvider.setOnClickListener(mClickListener);
- radioConsumer.setOnClickListener(mClickListener);
-
- signUp.setOnClickListener(mClickListener);
- signIn.setOnClickListener(mClickListener);
- signOut.setOnClickListener(mClickListener);
-
- remoteService.setOnClickListener(mClickListener);
- subscribeMQ.setOnClickListener(mClickListener);
-
- mProviderSample = new ProviderSample(getApplicationContext());
- mProviderSample.setHandler(mHandler);
-
- mNotiListener = new NotiListener(this);
- Intent intent = new Intent(
- "android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
- startActivity(intent);
- }
-
- @Override
- protected void onDestroy() {
- super.onDestroy();
- }
-
- public ProviderSample getProviderSample() {
- return mProviderSample;
- }
-
- Button.OnClickListener mClickListener = new View.OnClickListener() {
- public void onClick(View v) {
- switch (v.getId()) {
- case R.id.RadioProvider: {
- if (isStarted == false) {
- gAcceptor = true;
- showToast("Provider as acceptor is " + gAcceptor);
- } else
- showToast(
- "Start ProviderService again to change acceptor as provider");
- }
- break;
-
- case R.id.RadioConsumer: {
- if (isStarted == false) {
- gAcceptor = false;
- showToast("Provider as acceptor is " + gAcceptor);
- } else
- showToast(
- "Start ProviderService again to change acceptor as consumer");
- }
- break;
-
- case R.id.BtnStart: {
- if (isStarted == false) {
- Log.i(TAG, "Start Provider Service");
- TvLog.setText("Start Provider Service\n");
- mProviderSample.start(gAcceptor);
- isStarted = true;
- radioProvider.setEnabled(false);
- radioConsumer.setEnabled(false);
- // refreshToken();
-
- } else {
- Log.e(TAG, " Provider Service had already started");
- showToast(" Provider Service had already started");
- }
- }
- break;
-
- case R.id.BtnRegister: {
- if (isStarted == false) {
- Log.i(TAG, "Start Provider Service");
- TvLog.append("Register Topic : OCF_TOPIC1\n");
- TvLog.append("Register Topic : OCF_TOPIC2\n");
- TvLog.append("Register Topic : OCF_TOPIC3\n");
- TvLog.append("Register Topic : OCF_TOPIC4\n");
- showToast("Start Provider Service First");
- break;
- }
- mProviderSample.registerTopic();
-
- }
- break;
-
- case R.id.BtnSet: {
- if (isStarted == false) {
- Log.i(TAG, "Start Provider Service");
- TvLog.append("Set Topic : OCF_TOPIC1\n");
- TvLog.append("Set Topic : OCF_TOPIC2\n");
- TvLog.append("Set Topic : OCF_TOPIC3\n");
- TvLog.append("Set Topic : OCF_TOPIC4\n");
- showToast("Start Provider Service First");
- break;
- }
- if (gAcceptor == false) {
- showToast(
- "Operation Not Permitted: \nStart Provider Service with provider as acceptor");
- break;
- }
- mProviderSample.setTopic();
-
- }
- break;
-
- case R.id.BtnCreateNoti: {
-
- String id = Integer.toString(notiId); // generate
- // notificaion ID
- String title = editTextTitle.getText().toString();
- String body = editTextBody.getText().toString();
- String topic = editTextTopic.getText().toString();
-
- if (isStarted == false) {
- Log.e(TAG, "Fail to send NSMessage");
- showToast("Start ProviderService First");
- break;
- }
-
- // Build android noti object and send it to Notification
- // service receiver
- Notification.Builder notiBuilder = new Notification.Builder(
- getApplicationContext());
- notiBuilder.setContentTitle(title);
- notiBuilder.setContentText(body);
- notiBuilder.setSubText(topic);
- notiBuilder.setPriority(Notification.PRIORITY_MAX);
- notiBuilder.setDefaults(Notification.DEFAULT_ALL);
- notiBuilder.setSmallIcon(R.mipmap.ic_launcher);
- NotificationManager notiMgr = (NotificationManager) getSystemService(
- NOTIFICATION_SERVICE);
- notiMgr.notify(notiId, notiBuilder.build());
-
- Log.i(TAG, "#" + notiId + " notified ..");
- TvLog.append("Send Notitication(Msg ID: " + notiId + ")\n");
- notiId++;
- }
- break;
-
- case R.id.BtnStop: {
- if (isStarted == false) {
- Log.e(TAG, "Fail to stop service");
- showToast("Already Stopped");
- break;
- }
-
- mProviderSample.stop();
- isStarted = false;
- radioProvider.setEnabled(true);
- radioConsumer.setEnabled(true);
- showToast("Stopped ProviderService" + isStarted);
- TvLog.append("Stop Provider Service\n");
- }
- break;
-
- case R.id.BtnLog: {
-
- TvLog.setText("");
- }
- break;
- case R.id.signup: {
- if (isStarted == false) {
- Log.e(TAG, "Fail to Sign Up");
- showToast("Start ProviderService First");
- break;
- }
- TvLog.append("Initiating SignUp\n");
- signUp();
- }
- break;
- case R.id.signin: {
- if (isStarted == false) {
- Log.e(TAG, "Fail to Sign In");
- showToast("Start ProviderService First");
- break;
- }
- TvLog.append("Initiating SignIn\n");
- signIn();
- }
- break;
- case R.id.signout: {
- if (isStarted == false) {
- Log.e(TAG, "Fail to Sign out");
- showToast("Start ProviderService First");
- break;
- }
- TvLog.append("Initiating SignOut\n");
- signOut();
- }
- break;
- case R.id.remoteService: {
- remoteService.setEnabled(false);
- if (isStarted == false) {
- Log.e(TAG, "Fail to Enable/Disable RemoteService");
- showToast("Start ProviderService First");
- break;
- }
- if (gRemoteService) {
- TvLog.append("Enable Remote Service\n");
- mProviderSample.enableRemoteService(RemoteAddress);
- remoteService.setText(R.string.disableRemoteService);
- gRemoteService = false;
- remoteService.setEnabled(true);
- TvLog.append("EnableRemoteService success \n");
- } else {
- TvLog.append("Disable Remote Service\n");
- mProviderSample.disableRemoteService(RemoteAddress);
- remoteService.setText(R.string.enableRemoteService);
- gRemoteService = true;
- remoteService.setEnabled(true);
- TvLog.append("DisableRemoteService success\n");
- }
- }
- break;
- case R.id.subscribeMQService: {
- if (isStarted == false) {
- Log.e(TAG, "Fail to SubscribeMQService");
- showToast("Start ProviderService First");
- break;
- }
- final Dialog dialog = new Dialog(context);
- dialog.setContentView(R.layout.dialog_mq);
- dialog.setTitle("MQ Cloud Service Details");
-
- final EditText ip = (EditText) dialog
- .findViewById(R.id.EditTextIp);
- final EditText mqTopic = (EditText) dialog
- .findViewById(R.id.EditTextMqTopic);
- if (MQCloudAddress != null && MQCloudTopic != null) {
- ip.setText(MQCloudAddress);
- mqTopic.setText(MQCloudTopic);
- }
-
- Button dialogButton = (Button) dialog
- .findViewById(R.id.mqButtonOK);
-
- dialogButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- dialog.dismiss();
- MQCloudAddress = ip.getText().toString();
- MQCloudTopic = mqTopic.getText().toString();
- mProviderSample.subscribeMQService(
- MQCloudAddress, MQCloudTopic);
- TvLog.append("SubscribeMQService success\n");
- }
- });
- dialog.show();
- }
- break;
- }
- }
- };
-
- public void logMessage(final String text) {
- runOnUiThread(new Runnable() {
- public void run() {
- Message msg = new Message();
- msg.obj = text;
- TvLog.append(text + "\n");
- }
- });
- Log.i(TAG, text);
- }
-
- OcAccountManager.OnPostListener onSignUp = new OcAccountManager.OnPostListener() {
- @Override
- public synchronized void onPostCompleted(List<OcHeaderOption> list,
- OcRepresentation ocRepresentation) {
- logMessage("signUp was successful");
- runOnUiThread(new Runnable() {
- public void run() {
- signIn.setEnabled(true);
- signUp.setEnabled(false);
- }
- });
- try {
- mUserID = ocRepresentation.getValue("uid");
- mAccessToken = ocRepresentation.getValue("accesstoken");
- mRefreshtoken = ocRepresentation.getValue("refreshtoken");
-
- logMessage("\tuserID: " + mUserID);
- logMessage("\taccessToken: " + mAccessToken);
- logMessage("\trefreshToken: " + mRefreshtoken);
-
- if (ocRepresentation.hasAttribute("expiresin")) {
- int expiresIn = ocRepresentation.getValue("expiresin");
- logMessage("\texpiresIn: " + expiresIn);
- }
- } catch (OcException e) {
- Log.e(TAG, e.toString());
- }
- }
-
- @Override
- public synchronized void onPostFailed(Throwable throwable) {
- logMessage("Failed to signUp");
- if (throwable instanceof OcException) {
- OcException ocEx = (OcException) throwable;
- Log.e(TAG, ocEx.toString());
- ErrorCode errCode = ocEx.getErrorCode();
- logMessage("Error code: " + errCode);
- }
- }
- };
-
- OcAccountManager.OnPostListener onSignIn = new OcAccountManager.OnPostListener() {
- @Override
- public synchronized void onPostCompleted(List<OcHeaderOption> list,
- OcRepresentation ocRepresentation) {
- logMessage("signIn was successful");
- runOnUiThread(new Runnable() {
- public void run() {
- signIn.setEnabled(false);
- signOut.setEnabled(true);
- remoteService.setEnabled(true);
- }
- });
- }
-
- @Override
- public synchronized void onPostFailed(Throwable throwable) {
- logMessage("Failed to signIn");
- if (throwable instanceof OcException) {
- OcException ocEx = (OcException) throwable;
- Log.e(TAG, ocEx.toString());
- ErrorCode errCode = ocEx.getErrorCode();
- logMessage("Error code: " + errCode);
- if (ErrorCode.UNAUTHORIZED_REQ != errCode) {
- refreshToken();
- }
- }
- }
- };
-
- OcAccountManager.OnPostListener onSignOut = new OcAccountManager.OnPostListener() {
- @Override
- public synchronized void onPostCompleted(List<OcHeaderOption> list,
- OcRepresentation ocRepresentation) {
- logMessage("signOut was successful");
- runOnUiThread(new Runnable() {
- public void run() {
- signIn.setEnabled(true);
- signOut.setEnabled(false);
- remoteService.setEnabled(false);
- }
- });
-
- }
-
- @Override
- public synchronized void onPostFailed(Throwable throwable) {
- logMessage("Failed to signOut");
- if (throwable instanceof OcException) {
- OcException ocEx = (OcException) throwable;
- Log.e(TAG, ocEx.toString());
- ErrorCode errCode = ocEx.getErrorCode();
- logMessage("Error code: " + errCode);
- if (ErrorCode.UNAUTHORIZED_REQ != errCode) {
- refreshToken();
- }
- }
- }
- };
-
- @Override
- public void onPostCompleted(List<OcHeaderOption> ocHeaderOptions,
- OcRepresentation ocRepresentation) {
-
- }
-
- @Override
- public void onPostFailed(Throwable throwable) {
-
- }
-
- private void signIn() {
- try {
- if (mAccountManager == null) {
- mAccountManager = OcPlatform.constructAccountManagerObject(
- CIServer,
- EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP));
- }
-
- mAccountManager.signIn(mUserID, mAccessToken, onSignIn);
- } catch (OcException e) {
- e.printStackTrace();
- }
- }
-
- private void signOut() {
- try {
- logMessage("signOut");
- if (mAccountManager == null) {
- try {
- mAccountManager = OcPlatform.constructAccountManagerObject(
- CIServer,
- EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP));
- } catch (OcException e) {
- e.printStackTrace();
- }
- }
- mAccountManager.signOut(mAccessToken, onSignOut);
- signIn.setEnabled(false);
- signUp.setEnabled(true);
- remoteService.setEnabled(false);
- logMessage("signOut Successful");
- } catch (OcException e) {
- e.printStackTrace();
- }
- }
-
- private void signUp() {
- Intent intentLogin = new Intent(this, LoginActivity.class);
- startActivityForResult(intentLogin, REQUEST_LOGIN);
- }
-
- @Override
- public void onActivityResult(int requestCode, int resultCode, Intent data) {
- super.onActivityResult(requestCode, resultCode, data);
- if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_LOGIN) {
- mAuthCode = data.getStringExtra("authCode");
- mAuthProvider = data.getStringExtra("authProvider");
- logMessage("authCode: " + mAuthCode);
- logMessage("authProvider: " + mAuthProvider);
-
- final Dialog dialog = new Dialog(context);
- dialog.setContentView(R.layout.dialog_entry);
- dialog.setTitle("SignUp Acccount IP Address");
- final EditText ip = (EditText) dialog
- .findViewById(R.id.EditTextEntry);
- if (RemoteAddress != null) {
- ip.setText(RemoteAddress);
- }
- Button dialogButton = (Button) dialog
- .findViewById(R.id.entryButtonOK);
- dialogButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- dialog.dismiss();
- RemoteAddress = ip.getText().toString();
- CIServer = CI_SERVER_PREFIX + RemoteAddress;
- logMessage("server address for signup is: \n" + CIServer);
- try {
- mAccountManager = OcPlatform
- .constructAccountManagerObject(CIServer, EnumSet
- .of(OcConnectivityType.CT_ADAPTER_TCP));
- logMessage("Calling signup API");
-
- if (mAuthProvider.equals("samsung")
- || mAuthProvider.equals("samsung-us"))
-
- {
- logMessage("Auth provider is samsung");
- Map<String, String> options = new HashMap<>();
- options.put("auth_server_url",
- "us-auth2.samsungosp.com");
- options.put("api_server_url",
- "us-auth2.samsungosp.com");
- mAccountManager.signUp(mAuthProvider, mAuthCode,
- options, onSignUp);
- } else {
- mAccountManager.signUp(mAuthProvider, mAuthCode,
- onSignUp);
- }
- } catch (OcException e) {
- e.printStackTrace();
- }
- }
- });
- dialog.show();
- }
- }
-
- OcResource.OnPostListener onRefreshTokenPost = new OcResource.OnPostListener() {
- @Override
- public void onPostCompleted(List<OcHeaderOption> list,
- OcRepresentation ocRepresentation) {
- logMessage("RefreshToken Completed.");
- try {
- mAccessToken = ocRepresentation.getValue("accesstoken");
- mRefreshtoken = ocRepresentation.getValue("refreshtoken");
- } catch (OcException e) {
- e.printStackTrace();
- }
- signIn();
- }
-
- @Override
- public void onPostFailed(Throwable throwable) {
- logMessage("RefreshToken failed.");
- Log.d(TAG, "onRefreshTokenPost failed.");
- }
- };
-
- public void refreshToken() {
-
- if (deviceID == null) {
- final Dialog dialog = new Dialog(context);
- dialog.setContentView(R.layout.dialog_entry);
- dialog.setTitle("Enter Device Id");
- dialog.setCanceledOnTouchOutside(false);
- final EditText id = (EditText) dialog
- .findViewById(R.id.EditTextEntry);
-
- Button dialogButton = (Button) dialog
- .findViewById(R.id.entryButtonOK);
- dialogButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- dialog.dismiss();
- deviceID = id.getText().toString();
- }
- });
- dialog.show();
- }
- try {
- OcResource authResource = OcPlatform.constructResourceObject(
- CIServer, "/.well-known/ocf/account/tokenrefresh",
- EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP,
- OcConnectivityType.CT_IP_USE_V4),
- false, Arrays.asList("oic.wk.account"),
- Arrays.asList(OcPlatform.DEFAULT_INTERFACE));
- OcRepresentation rep = new OcRepresentation();
-
- showToast("RefreshToken in progress..");
- logMessage("RefreshToken in progress..");
- rep.setValue("di", deviceID);
- rep.setValue("granttype", "refresh_token");
- rep.setValue("refreshtoken", mRefreshtoken);
- rep.setValue("uid", mUserID);
- authResource.post(rep, new HashMap<String, String>(),
- onRefreshTokenPost);
- } catch (OcException e) {
- e.printStackTrace();
- }
-
- Log.d(TAG, "No error while executing login");
- }
-}
+++ /dev/null
-/*
-//******************************************************************
-//
-// Copyright 2016 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.iotivity.service.ns.sample.provider;
-
-import android.app.Notification;
-import android.os.Bundle;
-import android.service.notification.NotificationListenerService;
-import android.service.notification.StatusBarNotification;
-import android.util.Log;
-import org.iotivity.service.ns.common.MediaContents;
-import org.iotivity.service.ns.common.Message;
-import java.util.ArrayList;
-
-public class NotiListener extends NotificationListenerService {
-
- private final String TAG = "NS_JNI_NOTI_LISTENER";
- private static ProviderSample mProviderSample = null;
- private MainActivity mActivity = null;
- ArrayList mBlackSourceList = new ArrayList<String>();
-
- public NotiListener() {
-
- Log.i(TAG, "Create NotiListener");
- }
-
- public NotiListener(MainActivity activity) {
-
- Log.i(TAG, "Create NotiListener with MainActivity");
-
- this.mActivity = activity;
- this.mProviderSample = mActivity.getProviderSample();
-
- setBlackSourceList();
-
- if (mProviderSample == null) {
- Log.i(TAG, "Fail to get providerProxy instance");
- }
- }
-
- public void setBlackSourceList() {
-
- // set blacklist of app package name not to receive notification
- mBlackSourceList.add("android");
- mBlackSourceList.add("com.android.systemui");
- }
-
- @Override
- public void onNotificationPosted(StatusBarNotification sbn) {
- super.onNotificationPosted(sbn);
- Log.i(TAG, "Notification posted By package" + sbn.getPackageName());
-
- Bundle bundle = sbn.getNotification().extras;
- String source = null;
-
- // prevent not to send notification
- for (int i = 0; i < mBlackSourceList.size(); ++i) {
- if (sbn.getPackageName().equals(mBlackSourceList.get(i))) {
- return;
- }
- }
-
- // filter exception case : Some notification are generated twice
- if (sbn.getId() > 10000 || sbn.getId() < 0) {
- return;
- }
-
- // Temporary protocol code to display ICON on consumer app.
- // For example, consumer app shows KAKAOTALK Icon when receiving
- // Notification with SOURCE
- // that is set to KAKAO, otherwise it displays OCF Icon on current
- // sample app.
- if (sbn.getPackageName().equals("com.kakao.talk")) {
- source = "KAKAO";
- }
- else {
- source = "OCF";
- }
-
- Log.i(TAG, "Noti. Package Name : " + sbn.getPackageName());
- Log.i(TAG, "Noti. ID : " + sbn.getId());
-
- String id = Integer.toString(sbn.getId());
- String title = bundle.getString(Notification.EXTRA_TITLE, "");
- String body = bundle.getString(Notification.EXTRA_TEXT, "");
- String topic = bundle.getString(Notification.EXTRA_SUB_TEXT, "");
-
- Log.i(TAG, "onNotificationPosted .. ");
- Log.i(TAG, "source : " + source);
- Log.i(TAG, "Id : " + id);
- Log.i(TAG, "Title : " + title);
- Log.i(TAG, "Body : " + body);
-
- Message notiMessage = mProviderSample.createMessage();
- if(notiMessage == null)
- {
- Log.e(TAG, "CreateMessage Failed");
- return;
- }
- Log.i(TAG, "Message ID : " + notiMessage.getMessageId());
- Log.i(TAG, "Provider ID : " + notiMessage.getProviderId());
- notiMessage.setTitle(title);
- notiMessage.setContentText(body);
- notiMessage.setTopic(topic);
- notiMessage.setSourceName(source);
- notiMessage.setTTL(10);
- notiMessage.setTime("12:10");
- MediaContents media = new MediaContents("daasd");
- notiMessage.setMediaContents(media);
- if (mProviderSample != null) {
- mProviderSample.sendMessage(notiMessage);
- } else {
- Log.i(TAG, "providerExample is NULL");
- }
- }
-
- @Override
- public void onNotificationRemoved(StatusBarNotification sbn) {
- super.onNotificationRemoved(sbn);
-
- Bundle bundle = sbn.getNotification().extras;
-
- if (sbn.getPackageName().equals("android")) {
- return;
- }
-
- Log.i(TAG, "Noti. Package Name : " + sbn.getPackageName());
- Log.i(TAG, "Noti. ID : " + sbn.getId());
-
- if (mProviderSample.getMsgMap().containsKey(sbn.getId())) {
- if (mProviderSample.getMsgMap().get(sbn.getId()) == 2) {
- org.iotivity.service.ns.common.SyncInfo.SyncType type = org.iotivity.service.ns.common.SyncInfo.SyncType.READ;
- mProviderSample.sendSyncInfo(1, type);
- }
- }
- }
-}
+++ /dev/null
-/*
-//******************************************************************
-//
-// Copyright 2016 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.iotivity.service.ns.sample.provider;
-
-import android.content.Context;
-import android.os.*;
-import android.util.Log;
-import android.widget.Toast;
-
-import org.iotivity.base.ModeType;
-import org.iotivity.base.OcPlatform;
-import org.iotivity.base.OcResourceHandle;
-import org.iotivity.base.PlatformConfig;
-import org.iotivity.base.QualityOfService;
-import org.iotivity.base.ServiceType;
-import org.iotivity.service.ns.common.Message;
-import org.iotivity.service.ns.provider.*;
-import org.iotivity.service.ns.common.*;
-
-import java.util.HashMap;
-
-public class ProviderSample
- implements ProviderService.OnConsumerSubscribedListener,
- ProviderService.OnMessageSynchronizedListener {
-
- private static final String TAG = "NS_PROVIDER_SAMPLE";
-
- private Context mContext = null;
- private OcResourceHandle mResourceHandle;
- private ProviderService ioTNotification = null;
- private HashMap<String, Integer> msgMap;
-
- private Handler mHandler = null;
-
- private static final int CONSUMER_SUBSCRIBED = 1;
- private static final int MESSAGE_SYNC = 2;
-
- private static final int SYNC_READ = 0;
- private static final int SYNC_DISMISS = 1;
- private static final int SYNC_UNREAD = 2;
- private boolean gAcceptor;
- private Consumer gConsumer;
-
- public ProviderSample(Context context) {
- Log.i(TAG, "Create providerSample Instance");
-
- this.msgMap = new HashMap<>();
- this.mContext = context;
- ioTNotification = ProviderService.getInstance();
- }
-
- public void setHandler(Handler handler) {
- this.mHandler = handler;
- }
-
- private void configurePlatform() {
-
- PlatformConfig platformConfig = new PlatformConfig(mContext,
- ServiceType.IN_PROC, ModeType.CLIENT_SERVER, "0.0.0.0",
- 0, // Uses randomly available port
- QualityOfService.LOW);
-
- Log.i(TAG, "Configuring platform.");
- OcPlatform.Configure(platformConfig);
- try {
- OcPlatform.stopPresence(); // Initialize OcPlatform
- } catch (Exception e) {
- Log.e(TAG, "Exception: stopping presence when configuration step: "
- + e);
- }
- Log.i(TAG, "Configuration done Successfully");
- }
-
- public void start(boolean policy) {
- Log.i(TAG, "Start ProviderService -IN");
- configurePlatform();
- gAcceptor = policy;
- try {
- ioTNotification.start(this, this, policy, "Info", false);
- } catch (Exception e) {
- Log.e(TAG, "Exception: start : " + e);
- }
- Log.i(TAG, "Start ProviderService - OUT");
- }
-
- public void registerTopic() {
- Log.i(TAG, "Register Topics -IN");
- try {
- ioTNotification.registerTopic("OCF_TOPIC1");
- ioTNotification.registerTopic("OCF_TOPIC2");
- ioTNotification.registerTopic("OCF_TOPIC3");
- ioTNotification.registerTopic("OCF_TOPIC4");
- } catch (Exception e) {
- Log.e(TAG, "Exception: registerTopic : "+ e);
- }
-
- Log.i(TAG, "Start ProviderService - OUT");
- }
-
- public void setTopic() {
- Log.i(TAG, "Set Topic -IN");
- if (gConsumer == null) {
- return;
- }
- try {
- gConsumer.setTopic("OCF_TOPIC1");
- gConsumer.setTopic("OCF_TOPIC2");
- gConsumer.setTopic("OCF_TOPIC3");
- gConsumer.setTopic("OCF_TOPIC4");
- } catch (Exception e) {
- Log.e(TAG, "Exception: setTopic : " + e);
- }
-
- Log.i(TAG, "setTopic ProviderService - OUT");
- return;
- }
-
- public void stop() {
- Log.i(TAG, "Stop ProviderService - IN");
- try {
- OcPlatform.stopPresence();
- } catch (Exception e) {
- Log.e(TAG,"Exception: stopping presence when terminating NS server: "+ e);
- }
- try {
- ioTNotification.stop();
- } catch (Exception e) {
- Log.e(TAG, "Exception: stop : " + e);
- }
-
- Log.i(TAG, "Stop ProviderService - OUT");
- }
-
- public Message createMessage() {
- Log.i(TAG, "createMessage ProviderService - IN");
- Message message = null;
- try {
- message = ioTNotification.createMessage();
- } catch (Exception e) {
- Log.e(TAG, "Exception: createMessage : " + e);
- }
- Log.i(TAG, "createMessage ProviderService - OUT");
- return message;
- }
-
- public void sendMessage(Message notiMessage) {
- Log.i(TAG, "SendMessage ProviderService - IN");
-
- try {
- ioTNotification.sendMessage(notiMessage);
- } catch (Exception e) {
- Log.e(TAG, "Exception: sendMessage : " + e);
- }
-
- Log.i(TAG, "SendMessage ProviderService - OUT");
- mHandler.post(new Runnable() {
- @Override
- public void run() {
- Toast.makeText(mContext, "Notification sent",
- Toast.LENGTH_SHORT).show();
- }
- });
- }
-
- public void sendSyncInfo(long messageId, SyncInfo.SyncType syncType) {
- Log.i(TAG, "SendSyncInfo ProviderService - IN");
- if (msgMap.containsKey(messageId)) {
- if (msgMap.get(messageId) == SYNC_UNREAD) {
- try {
- ioTNotification.sendSyncInfo(messageId, syncType);
- Log.i(TAG, "Notification Sync ");
- } catch (Exception e) {
- Log.e(TAG, "Exception: sendSyncInfo : " + e);
- }
- Log.i(TAG, "SendSyncInfo ProviderService - OUT");
- msgMap.put("ID: " + messageId, SYNC_READ);
- }
- }
- }
-
- public void enableRemoteService(String servAdd) {
- Log.i(TAG, "EnableRemoteService ProviderService - IN");
- try {
- ioTNotification.enableRemoteService(servAdd);
- } catch (Exception e) {
- Log.e(TAG, "Exception: enableRemoteService : " + e);
- }
- Log.i(TAG, "EnableRemoteService ProviderService - OUT");
- return;
- }
-
- public void disableRemoteService(String servAdd) {
- Log.i(TAG, "DisableRemoteService ProviderService - IN");
- try {
- ioTNotification.disableRemoteService(servAdd);
- } catch (Exception e) {
- Log.e(TAG, "Exception: disableRemoteService : " + e);
- }
- Log.i(TAG, "DisableRemoteService ProviderService - OUT");
- return;
- }
-
- public void subscribeMQService(String servAdd, String topicName) {
- Log.i(TAG, "SubscribeMQService ProviderService - IN");
- try {
- ioTNotification.subscribeMQService(servAdd, topicName);
- } catch (Exception e) {
- Log.e(TAG, "Exception: subscribeMQService : " + e);
- }
- Log.i(TAG, "SubscribeMQService ProviderService - OUT");
- return;
- }
-
- public void acceptSubscription(Consumer consumer, boolean accepted) {
- Log.i(TAG, "AcceptSubscription ProviderService - IN");
- try {
- consumer.acceptSubscription(accepted);
- } catch (Exception e) {
- Log.e(TAG, "Exception: acceptSubscription : " + e);
- }
- Log.i(TAG, "AcceptSubscription ProviderService - OUT");
- }
-
- @Override
- public void onConsumerSubscribed(Consumer consumer) {
- Log.i(TAG, "onConsumerSubscribed - IN");
- gConsumer = consumer;
- acceptSubscription(consumer, true);
- android.os.Message msg = mHandler.obtainMessage(CONSUMER_SUBSCRIBED,
- "Consumer Id: " + consumer.getConsumerId());
- mHandler.sendMessage(msg);
- Log.i(TAG, "onConsumerSubscribed - OUT");
- }
-
- @Override
- public void onMessageSynchronized(SyncInfo syncInfo) {
- Log.i(TAG,
- "Received SyncInfo with messageID: " + syncInfo.getMessageId());
- android.os.Message msg = mHandler.obtainMessage(MESSAGE_SYNC,
- "Message Id: " + syncInfo.getMessageId());
- mHandler.sendMessage(msg);
- }
-
- public HashMap<String, Integer> getMsgMap() {
- return msgMap;
- }
-}
+++ /dev/null
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:id="@+id/loginLayout"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical"
- tools:context=".LoginActivity">
-
- <WebView
- android:id="@+id/webView"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:visibility="visible" />
-
-</LinearLayout>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="utf-8"?>\r
-<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"\r
- xmlns:tools="http://schemas.android.com/tools"\r
- android:layout_width="match_parent"\r
- android:layout_height="match_parent"\r
- android:paddingBottom="@dimen/activity_vertical_margin"\r
- android:paddingLeft="@dimen/activity_horizontal_margin"\r
- android:paddingRight="@dimen/activity_horizontal_margin"\r
- android:paddingTop="@dimen/activity_vertical_margin"\r
- tools:context=".MainActivity">\r
-\r
- <ScrollView\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:fillViewport="true">\r
- <LinearLayout\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:paddingLeft="1dp"\r
- android:paddingRight="1dp"\r
- android:orientation="vertical" >\r
-\r
-\r
- <LinearLayout\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:paddingLeft="5dp"\r
- android:paddingRight="5dp"\r
- android:orientation="horizontal"\r
- android:weightSum="1">\r
-\r
- <Button\r
- android:layout_height="wrap_content"\r
- android:layout_width="150dp"\r
- android:id="@+id/BtnStart"\r
- android:text="START"/>\r
-\r
- <Button\r
- android:layout_height="wrap_content"\r
- android:layout_width="150dp"\r
- android:id="@+id/BtnStop"\r
- android:text="STOP" />\r
- </LinearLayout>\r
-\r
- <LinearLayout\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:paddingLeft="5dp"\r
- android:paddingRight="5dp"\r
- android:orientation="horizontal"\r
- android:weightSum="1">\r
-\r
- <RadioGroup\r
- android:id="@+id/RadioGroup"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:layout_alignParentLeft="true"\r
- android:orientation='horizontal'>\r
- <TextView\r
- android:layout_width="wrap_content"\r
- android:layout_height="wrap_content"\r
- android:text="ACCEPTOR: "\r
- android:id="@+id/textview"\r
- android:checked="false" />\r
- <RadioButton\r
- android:layout_width="wrap_content"\r
- android:layout_height="wrap_content"\r
- android:text="Provider"\r
- android:id="@+id/RadioProvider"\r
- android:checked="true" />\r
-\r
- <RadioButton\r
- android:layout_width="wrap_content"\r
- android:layout_height="wrap_content"\r
- android:text="Consumer"\r
- android:id="@+id/RadioConsumer"\r
- android:checked="false" />\r
-\r
- </RadioGroup>\r
- </LinearLayout>\r
- <LinearLayout\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:paddingLeft="5dp"\r
- android:paddingRight="5dp"\r
- android:orientation="horizontal"\r
- android:weightSum="1">\r
-\r
- <Button\r
- android:layout_height="wrap_content"\r
- android:layout_width="100dp"\r
- android:id="@+id/signup"\r
- android:text="Sign Up"/>\r
-\r
- <Button\r
- android:layout_height="wrap_content"\r
- android:layout_width="100dp"\r
- android:id="@+id/signin"\r
- android:text="Sign In" />\r
- <Button\r
- android:layout_height="wrap_content"\r
- android:layout_width="100dp"\r
- android:id="@+id/signout"\r
- android:text="Sign Out" />\r
- </LinearLayout>\r
- <LinearLayout\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:paddingLeft="5dp"\r
- android:paddingRight="5dp"\r
- android:orientation="horizontal"\r
- android:weightSum="1">\r
-\r
- <Button\r
- android:layout_height="wrap_content"\r
- android:layout_width="150dp"\r
- android:id="@+id/remoteService"\r
- android:text="Enable Remote Service"/>\r
-\r
- <Button\r
- android:layout_height="wrap_content"\r
- android:layout_width="150dp"\r
- android:id="@+id/subscribeMQService"\r
- android:text="Subscribe MQ Service" />\r
- </LinearLayout>\r
- <LinearLayout\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:paddingLeft="5dp"\r
- android:paddingRight="5dp"\r
- android:orientation="horizontal"\r
- android:weightSum="1">\r
-\r
- <Button\r
- android:layout_height="wrap_content"\r
- android:layout_width="150dp"\r
- android:id="@+id/BtnRegister"\r
- android:text="@string/btn_reg"/>\r
-\r
- <Button\r
- android:layout_height="wrap_content"\r
- android:layout_width="150dp"\r
- android:id="@+id/BtnSet"\r
- android:text="@string/btn_set" />\r
- </LinearLayout>\r
-\r
- <LinearLayout\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:paddingLeft="5dp"\r
- android:paddingRight="5dp"\r
- android:orientation="horizontal" >\r
-\r
- <Button\r
- android:layout_height="wrap_content"\r
- android:layout_width="wrap_content"\r
- android:id="@+id/BtnTitle"\r
- android:text="@string/btn_title"\r
- android:onClick="selfDestruct" />\r
-\r
- <EditText\r
- android:id="@+id/EditTextTitle"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:windowSoftInputMode="stateHidden"\r
- android:hint="Add Message Title" />\r
- </LinearLayout>\r
-\r
- <LinearLayout\r
- android:id="@+id/LinearBody"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:paddingLeft="5dp"\r
- android:paddingRight="5dp"\r
- android:orientation="horizontal" >\r
-\r
- <Button\r
- android:layout_height="wrap_content"\r
- android:layout_width="wrap_content"\r
- android:id="@+id/BtnBody"\r
- android:text="@string/btn_body"\r
- android:onClick="selfDestruct" />\r
-\r
- <EditText\r
- android:id="@+id/EditTextBody"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:windowSoftInputMode="stateHidden"\r
- android:hint="Add Message Body" />\r
- </LinearLayout>\r
-\r
- <LinearLayout\r
- android:id="@+id/Topic"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:paddingLeft="5dp"\r
- android:paddingRight="5dp"\r
- android:orientation="horizontal" >\r
-\r
- <Button\r
- android:layout_height="wrap_content"\r
- android:layout_width="wrap_content"\r
- android:id="@+id/BtnTopic"\r
- android:text="@string/btn_topic"\r
- android:onClick="selfDestruct" />\r
-\r
- <EditText\r
- android:id="@+id/EditTextTopic"\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:windowSoftInputMode="stateHidden"\r
- android:hint="OCF_TOPIC1 (1-4)" />\r
- </LinearLayout>\r
-\r
- <Button\r
- android:layout_gravity="center_vertical|center_horizontal"\r
- android:layout_height="wrap_content"\r
- android:layout_width="match_parent"\r
- android:id="@+id/BtnCreateNoti"\r
- android:text="@string/btn_create_noti"\r
- />\r
- <Button\r
- android:layout_gravity="center_vertical|center_horizontal"\r
- android:layout_height="wrap_content"\r
- android:layout_width="match_parent"\r
- android:id="@+id/BtnLog"\r
- android:text="@string/btn_log"\r
- android:layout_alignParentBottom="true"\r
- android:layout_centerHorizontal="true" />\r
- <LinearLayout\r
- android:layout_width="match_parent"\r
- android:layout_height="10dp">\r
- </LinearLayout>\r
-\r
- <ScrollView\r
- android:layout_width="match_parent"\r
- android:layout_height="wrap_content"\r
- android:fillViewport="true">\r
-\r
- <LinearLayout\r
- android:layout_width="match_parent"\r
- android:layout_height="250dp"\r
- android:paddingLeft="5dp"\r
- android:paddingRight="5dp"\r
- android:orientation="horizontal" >\r
-\r
- <TextView\r
- android:layout_gravity="center_vertical|center_horizontal"\r
- android:layout_height="1000dp"\r
- android:layout_width="match_parent"\r
- android:scrollbars="vertical"\r
- android:id="@+id/TvLog"\r
- android:text="Log.."/>\r
- </LinearLayout>\r
-\r
- </ScrollView>\r
-\r
- </LinearLayout>\r
- </ScrollView>\r
-</RelativeLayout>\r
+++ /dev/null
-<?xml version="1.0" encoding="utf-8"?>
-<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent" >
-
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:paddingLeft="1dp"
- android:paddingRight="1dp"
- android:orientation="vertical" >
-
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:paddingLeft="5dp"
- android:paddingRight="5dp"
- android:orientation="horizontal" >
-
- <Button
- android:layout_height="wrap_content"
- android:layout_width="wrap_content"
- android:id="@+id/BtnAuth"
- android:text="@string/btn_auth"
- android:onClick="selfDestruct" />
-
- <EditText
- android:id="@+id/EditTextAuth"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:windowSoftInputMode="stateHidden"
- android:hint="Add Auth Provider Name" />
- </LinearLayout>
-
- <LinearLayout
- android:id="@+id/LinearBody"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:paddingLeft="5dp"
- android:paddingRight="5dp"
- android:orientation="horizontal" >
-
- <Button
- android:layout_height="wrap_content"
- android:layout_width="wrap_content"
- android:id="@+id/BtnUrl"
- android:text="@string/btn_url"
- android:onClick="selfDestruct" />
-
- <EditText
- android:id="@+id/EditTextUrl"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:windowSoftInputMode="stateHidden"
- android:hint="Add Login Account URL" />
- </LinearLayout>
-
- <Button
- android:layout_gravity="center_vertical|center_horizontal"
- android:layout_height="wrap_content"
- android:layout_width="match_parent"
- android:id="@+id/dialogButtonOK"
- android:text="@string/btn_ok"
- />
- </LinearLayout>
-
-
-</RelativeLayout>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="utf-8"?>
-<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent" >
-
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:paddingLeft="1dp"
- android:paddingRight="1dp"
- android:orientation="vertical" >
-
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:paddingLeft="5dp"
- android:paddingRight="5dp"
- android:orientation="horizontal" >
-
- <EditText
- android:id="@+id/EditTextEntry"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:windowSoftInputMode="stateHidden"
- android:hint="Add Required Details" />
- </LinearLayout>
-
-
- <Button
- android:layout_gravity="center_vertical|center_horizontal"
- android:layout_height="wrap_content"
- android:layout_width="match_parent"
- android:id="@+id/entryButtonOK"
- android:text="@string/btn_ok"
- />
- </LinearLayout>
-
-
-</RelativeLayout>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="utf-8"?>
-<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent" >
-
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:paddingLeft="1dp"
- android:paddingRight="1dp"
- android:orientation="vertical" >
-
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:paddingLeft="5dp"
- android:paddingRight="5dp"
- android:orientation="horizontal" >
-
- <Button
- android:layout_height="wrap_content"
- android:layout_width="wrap_content"
- android:id="@+id/BtnAuth"
- android:text="@string/btn_addr"
- android:onClick="selfDestruct" />
-
- <EditText
- android:id="@+id/EditTextIp"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:windowSoftInputMode="stateHidden"
- android:hint="Add MQ Server IP Address" />
- </LinearLayout>
-
- <LinearLayout
- android:id="@+id/LinearBody"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:paddingLeft="5dp"
- android:paddingRight="5dp"
- android:orientation="horizontal" >
-
- <Button
- android:layout_height="wrap_content"
- android:layout_width="wrap_content"
- android:id="@+id/BtnTopic"
- android:text="@string/btn_topic"
- android:onClick="selfDestruct" />
-
- <EditText
- android:id="@+id/EditTextMqTopic"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:windowSoftInputMode="stateHidden"
- android:hint="Add MQ Topic name" />
- </LinearLayout>
-
- <Button
- android:layout_gravity="center_vertical|center_horizontal"
- android:layout_height="wrap_content"
- android:layout_width="match_parent"
- android:id="@+id/mqButtonOK"
- android:text="@string/btn_ok"
- />
- </LinearLayout>
-
-
-</RelativeLayout>
\ No newline at end of file
+++ /dev/null
-<resources>\r
- <!-- Example customization of dimensions originally defined in res/values/dimens.xml\r
- (such as screen margins) for screens with more than 820dp of available width. This\r
- would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively). -->\r
- <dimen name="activity_horizontal_margin">64dp</dimen>\r
-</resources>\r
+++ /dev/null
-<?xml version="1.0" encoding="utf-8"?>\r
-<resources>\r
- <color name="colorPrimary">#3F51B5</color>\r
- <color name="colorPrimaryDark">#303F9F</color>\r
- <color name="colorAccent">#FF4081</color>\r
-</resources>\r
+++ /dev/null
-<resources>\r
- <!-- Default screen margins, per the Android Design guidelines. -->\r
- <dimen name="activity_horizontal_margin">16dp</dimen>\r
- <dimen name="activity_vertical_margin">16dp</dimen>\r
-</resources>\r
+++ /dev/null
-<resources>\r
- <string name="app_name">NotificationProviderExample</string>\r
- <string name="btn_title">Title</string>\r
- <string name="btn_body">Body</string>\r
- <string name="btn_topic">Topic</string>\r
- <string name="btn_reg">Register Topic</string>\r
- <string name="btn_set">Set Topic</string>\r
- <string name="btn_send">Send Notification</string>\r
- <string name="btn_create_noti">Send Notification</string>\r
- <string name="btn_log">Clear Logs</string>\r
- <string name="enableRemoteService">Enable Remote Service</string>\r
- <string name="disableRemoteService">Disable Remote Service</string>\r
- <string name="btn_auth">Auth</string>\r
- <string name="btn_url"> URL</string>\r
- <string name="btn_addr"> Addr. </string>\r
- <string name="btn_ok">Enter Details</string>\r
-</resources>\r
+++ /dev/null
-<resources>\r
-\r
- <!--\r
- Base application theme, dependent on API level. This theme is replaced\r
- by AppBaseTheme from res/values-vXX/styles.xml on newer devices.\r
- -->\r
- <style name="AppBaseTheme" parent="android:Theme.Light">\r
- <!--\r
- Theme customizations available in newer API levels can go in\r
- res/values-vXX/styles.xml, while customizations related to\r
- backward-compatibility can go here.\r
- -->\r
- </style>\r
-\r
- <!-- Application theme. -->\r
- <style name="AppTheme" parent="AppBaseTheme">\r
- <!-- All customizations that are NOT specific to a particular API-level can go here. -->\r
- </style>\r
-\r
-</resources>
\ No newline at end of file
+++ /dev/null
-// Top-level build file where you can add configuration options common to all sub-projects/modules.
-
-buildscript {
- repositories {
- jcenter()
- }
- dependencies {
- classpath 'com.android.tools.build:gradle:1.3.0'
-
- // NOTE: Do not place your application dependencies here; they belong
- // in the individual module build.gradle files
- }
-}
-
-allprojects {
- repositories {
- jcenter()
-
- flatDir {
- dirs '../../../../android/notification-service/build/outputs/aar'
- dirs '../../../../../../android/android_api/base/build/outputs/aar'
- }
- }
-}
-
-task clean(type: Delete) {
- delete rootProject.buildDir
-}
+++ /dev/null
-@if "%DEBUG%" == "" @echo off\r
-@rem ##########################################################################\r
-@rem\r
-@rem Gradle startup script for Windows\r
-@rem\r
-@rem ##########################################################################\r
-\r
-@rem Set local scope for the variables with windows NT shell\r
-if "%OS%"=="Windows_NT" setlocal\r
-\r
-@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.\r
-set DEFAULT_JVM_OPTS=\r
-\r
-set DIRNAME=%~dp0\r
-if "%DIRNAME%" == "" set DIRNAME=.\r
-set APP_BASE_NAME=%~n0\r
-set APP_HOME=%DIRNAME%\r
-\r
-@rem Find java.exe\r
-if defined JAVA_HOME goto findJavaFromJavaHome\r
-\r
-set JAVA_EXE=java.exe\r
-%JAVA_EXE% -version >NUL 2>&1\r
-if "%ERRORLEVEL%" == "0" goto init\r
-\r
-echo.\r
-echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.\r
-echo.\r
-echo Please set the JAVA_HOME variable in your environment to match the\r
-echo location of your Java installation.\r
-\r
-goto fail\r
-\r
-:findJavaFromJavaHome\r
-set JAVA_HOME=%JAVA_HOME:"=%\r
-set JAVA_EXE=%JAVA_HOME%/bin/java.exe\r
-\r
-if exist "%JAVA_EXE%" goto init\r
-\r
-echo.\r
-echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%\r
-echo.\r
-echo Please set the JAVA_HOME variable in your environment to match the\r
-echo location of your Java installation.\r
-\r
-goto fail\r
-\r
-:init\r
-@rem Get command-line arguments, handling Windowz variants\r
-\r
-if not "%OS%" == "Windows_NT" goto win9xME_args\r
-if "%@eval[2+2]" == "4" goto 4NT_args\r
-\r
-:win9xME_args\r
-@rem Slurp the command line arguments.\r
-set CMD_LINE_ARGS=\r
-set _SKIP=2\r
-\r
-:win9xME_args_slurp\r
-if "x%~1" == "x" goto execute\r
-\r
-set CMD_LINE_ARGS=%*\r
-goto execute\r
-\r
-:4NT_args\r
-@rem Get arguments from the 4NT Shell from JP Software\r
-set CMD_LINE_ARGS=%$\r
-\r
-:execute\r
-@rem Setup the command line\r
-\r
-set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar\r
-\r
-@rem Execute Gradle\r
-"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%\r
-\r
-:end\r
-@rem End local scope for the variables with windows NT shell\r
-if "%ERRORLEVEL%"=="0" goto mainEnd\r
-\r
-:fail\r
-rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of\r
-rem the _cmd.exe /c_ return code!\r
-if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1\r
-exit /b 1\r
-\r
-:mainEnd\r
-if "%OS%"=="Windows_NT" endlocal\r
-\r
-:omega\r
+++ /dev/null
-include ':app'\r
+++ /dev/null
-#//******************************************************************
-#//
-#// Copyright 2016 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.
-#//
-#//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-SConscript('NotiProviderExample/SConscript')
-SConscript('NotiConsumerExample/SConscript')
+++ /dev/null
-.gradle
-/local.properties
-/.idea/workspace.xml
-/.idea/libraries
-.DS_Store
-/build/*
-/resource-container/build/*
-/resource-container/src/main/obj/*
-/resource-container/src/main/libs/*
+++ /dev/null
-import os
-import platform
-Import('env')
-
-android_home = env.get('ANDROID_HOME')
-
-ANDROID_TARGET_ARCH = env.get('TARGET_ARCH')
-if env.get('RELEASE'):
- ANDROID_RELEASE="release"
-else:
- ANDROID_RELEASE="debug"
-
-os.environ['ANDROID_HOME'] = env.get('ANDROID_HOME')
-os.environ['ANDROID_NDK_HOME'] = env.get('ANDROID_NDK')
-
-if not os.path.exists(android_home + '/platforms/android-21') or not os.path.exists(android_home + '/build-tools/20.0.0'):
- print '''
-***************************************** Info ********************************
-* Either 'Android API 21' is not installed or 'Android SDK Build Tools *
-* 20.0.0' is not installed. The Android SDK Manager will now open. Please *
-* be sure to deselect all options, then select the following 2 packages: *
-* 1. Under "Tools" select "Android SDK Build-tools" Revision 20. *
-* 2. Under "Android 5.0.1 (API 21)" select "SDK Platform" *
-* 3. Continue by selecting "Install 2 Packages" *
-* *
-* NOTE: If you have an http proxy, please press ctrl+c now and edit/create *
-* the following file in your $HOME directory as follows: *
-* *
-* Edit/Create file: "$HOME/.android/androidtool.cfg" *
-* *
-* http.proxyPort=<YOUR_PORT_NUMBER> *
-* sdkman.monitor.density=108 *
-* http.proxyHost=<YOUR_HTTP_PROXY_ADDRESS> *
-* sdkman.show.update.only=true *
-* sdkman.ask.adb.restart=false *
-* sdkman.force.http=true *
-* sdkman.show.updateonly=true *
-* *
-*******************************************************************************
-
-...Opening Android SDK Manager now. Once you are finished, the build will continue.
-'''
- os.system(android_home + '/tools/android')
-
-def ensure_libs(target, source, env):
- return target, [source, env.get('BUILD_DIR') + 'librcs_container.so']
-
-jdk_env = Environment(ENV=os.environ)
-jdk_env['BUILDERS']['Gradle'] = Builder(action = env.get('ANDROID_GRADLE') +
- ' build -bservice/resource-container/android/build.gradle -PTARGET_ARCH=%s -PRELEASE=%s --stacktrace' %(ANDROID_TARGET_ARCH, ANDROID_RELEASE),
- emitter = ensure_libs)
-jdk_env['BUILD_DIR'] = env.get('BUILD_DIR')
-
-jdk_env.Gradle(target="resource-container/objs",
- source="resource-container/src/main/java/org/iotivity/service/resourcecontainer/RcsBundleInfo.java")
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<module external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$" external.system.id="GRADLE" type="JAVA_MODULE" version="4">
- <component name="FacetManager">
- <facet type="java-gradle" name="Java-Gradle">
- <configuration>
- <option name="BUILD_FOLDER_PATH" value="$MODULE_DIR$/build" />
- </configuration>
- </facet>
- </component>
- <component name="NewModuleRootManager" inherit-compiler-output="false">
- <output url="file://$MODULE_DIR$/build/classes/main" />
- <output-test url="file://$MODULE_DIR$/build/classes/test" />
- <exclude-output />
- <content url="file://$MODULE_DIR$">
- <excludeFolder url="file://$MODULE_DIR$/.gradle" />
- </content>
- <orderEntry type="inheritedJdk" />
- <orderEntry type="sourceFolder" forTests="false" />
- </component>
-</module>
-
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-// Top-level build file where you can add configuration options common to all sub-projects/modules.
-
-buildscript {
- repositories {
- jcenter()
- }
- dependencies {
- classpath 'com.android.tools.build:gradle:1.3.0'
-
- // NOTE: Do not place your application dependencies here; they belong
- // in the individual module build.gradle files
- }
-}
-
-allprojects {
- repositories {
- jcenter {
- url "http://jcenter.bintray.com/"
- }
- }
-}
+++ /dev/null
-#
-# //******************************************************************
-# //
-# // Copyright 2015 Intel Corporation.
-# //
-# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-# //
-# // 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.
-# //
-# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#
-
-# Project-wide Gradle settings.
-
-# IDE (e.g. Android Studio) users:
-# Gradle settings configured through the IDE *will override*
-# any settings specified in this file.
-
-# For more details on how to configure your build environment visit
-# http://www.gradle.org/docs/current/userguide/build_environment.html
-
-# Specifies the JVM arguments used for the daemon process.
-# The setting is particularly useful for tweaking memory settings.
-# Default value: -Xmx10248m -XX:MaxPermSize=256m
-# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
-
-# When configured, Gradle will run in incubating parallel mode.
-# This option should only be used with decoupled projects. More details, visit
-# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
-# org.gradle.parallel=true
+++ /dev/null
-#!/usr/bin/env bash
-
-##############################################################################
-##
-## Gradle start up script for UN*X
-##
-##############################################################################
-
-# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
-DEFAULT_JVM_OPTS=""
-
-APP_NAME="Gradle"
-APP_BASE_NAME=`basename "$0"`
-
-# Use the maximum available, or set MAX_FD != -1 to use that value.
-MAX_FD="maximum"
-
-warn ( ) {
- echo "$*"
-}
-
-die ( ) {
- echo
- echo "$*"
- echo
- exit 1
-}
-
-# OS specific support (must be 'true' or 'false').
-cygwin=false
-msys=false
-darwin=false
-case "`uname`" in
- CYGWIN* )
- cygwin=true
- ;;
- Darwin* )
- darwin=true
- ;;
- MINGW* )
- msys=true
- ;;
-esac
-
-# For Cygwin, ensure paths are in UNIX format before anything is touched.
-if $cygwin ; then
- [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
-fi
-
-# Attempt to set APP_HOME
-# Resolve links: $0 may be a link
-PRG="$0"
-# Need this for relative symlinks.
-while [ -h "$PRG" ] ; do
- ls=`ls -ld "$PRG"`
- link=`expr "$ls" : '.*-> \(.*\)$'`
- if expr "$link" : '/.*' > /dev/null; then
- PRG="$link"
- else
- PRG=`dirname "$PRG"`"/$link"
- fi
-done
-SAVED="`pwd`"
-cd "`dirname \"$PRG\"`/" >&-
-APP_HOME="`pwd -P`"
-cd "$SAVED" >&-
-
-CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
-
-# Determine the Java command to use to start the JVM.
-if [ -n "$JAVA_HOME" ] ; then
- if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
- # IBM's JDK on AIX uses strange locations for the executables
- JAVACMD="$JAVA_HOME/jre/sh/java"
- else
- JAVACMD="$JAVA_HOME/bin/java"
- fi
- if [ ! -x "$JAVACMD" ] ; then
- die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
-
-Please set the JAVA_HOME variable in your environment to match the
-location of your Java installation."
- fi
-else
- JAVACMD="java"
- which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
-
-Please set the JAVA_HOME variable in your environment to match the
-location of your Java installation."
-fi
-
-# Increase the maximum file descriptors if we can.
-if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
- MAX_FD_LIMIT=`ulimit -H -n`
- if [ $? -eq 0 ] ; then
- if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
- MAX_FD="$MAX_FD_LIMIT"
- fi
- ulimit -n $MAX_FD
- if [ $? -ne 0 ] ; then
- warn "Could not set maximum file descriptor limit: $MAX_FD"
- fi
- else
- warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
- fi
-fi
-
-# For Darwin, add options to specify how the application appears in the dock
-if $darwin; then
- GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
-fi
-
-# For Cygwin, switch paths to Windows format before running java
-if $cygwin ; then
- APP_HOME=`cygpath --path --mixed "$APP_HOME"`
- CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
-
- # We build the pattern for arguments to be converted via cygpath
- ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
- SEP=""
- for dir in $ROOTDIRSRAW ; do
- ROOTDIRS="$ROOTDIRS$SEP$dir"
- SEP="|"
- done
- OURCYGPATTERN="(^($ROOTDIRS))"
- # Add a user-defined pattern to the cygpath arguments
- if [ "$GRADLE_CYGPATTERN" != "" ] ; then
- OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
- fi
- # Now convert the arguments - kludge to limit ourselves to /bin/sh
- i=0
- for arg in "$@" ; do
- CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
- CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
-
- if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
- eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
- else
- eval `echo args$i`="\"$arg\""
- fi
- i=$((i+1))
- done
- case $i in
- (0) set -- ;;
- (1) set -- "$args0" ;;
- (2) set -- "$args0" "$args1" ;;
- (3) set -- "$args0" "$args1" "$args2" ;;
- (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
- (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
- (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
- (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
- (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
- (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
- esac
-fi
-
-# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
-function splitJvmOpts() {
- JVM_OPTS=("$@")
-}
-eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
-JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
-
-exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
+++ /dev/null
-@if "%DEBUG%" == "" @echo off
-@rem ##########################################################################
-@rem
-@rem Gradle startup script for Windows
-@rem
-@rem ##########################################################################
-
-@rem Set local scope for the variables with windows NT shell
-if "%OS%"=="Windows_NT" setlocal
-
-@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
-set DEFAULT_JVM_OPTS=
-
-set DIRNAME=%~dp0
-if "%DIRNAME%" == "" set DIRNAME=.
-set APP_BASE_NAME=%~n0
-set APP_HOME=%DIRNAME%
-
-@rem Find java.exe
-if defined JAVA_HOME goto findJavaFromJavaHome
-
-set JAVA_EXE=java.exe
-%JAVA_EXE% -version >NUL 2>&1
-if "%ERRORLEVEL%" == "0" goto init
-
-echo.
-echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
-echo.
-echo Please set the JAVA_HOME variable in your environment to match the
-echo location of your Java installation.
-
-goto fail
-
-:findJavaFromJavaHome
-set JAVA_HOME=%JAVA_HOME:"=%
-set JAVA_EXE=%JAVA_HOME%/bin/java.exe
-
-if exist "%JAVA_EXE%" goto init
-
-echo.
-echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
-echo.
-echo Please set the JAVA_HOME variable in your environment to match the
-echo location of your Java installation.
-
-goto fail
-
-:init
-@rem Get command-line arguments, handling Windowz variants
-
-if not "%OS%" == "Windows_NT" goto win9xME_args
-if "%@eval[2+2]" == "4" goto 4NT_args
-
-:win9xME_args
-@rem Slurp the command line arguments.
-set CMD_LINE_ARGS=
-set _SKIP=2
-
-:win9xME_args_slurp
-if "x%~1" == "x" goto execute
-
-set CMD_LINE_ARGS=%*
-goto execute
-
-:4NT_args
-@rem Get arguments from the 4NT Shell from JP Software
-set CMD_LINE_ARGS=%$
-
-:execute
-@rem Setup the command line
-
-set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
-
-@rem Execute Gradle
-"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
-
-:end
-@rem End local scope for the variables with windows NT shell
-if "%ERRORLEVEL%"=="0" goto mainEnd
-
-:fail
-rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
-rem the _cmd.exe /c_ return code!
-if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
-exit /b 1
-
-:mainEnd
-if "%OS%"=="Windows_NT" endlocal
-
-:omega
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-DISCLAIMER: The Android support for the resource container is experimental.
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<module external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$/.." external.system.id="GRADLE" external.system.module.group="android_api" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
- <component name="FacetManager">
- <facet type="android-gradle" name="Android-Gradle">
- <configuration>
- <option name="GRADLE_PROJECT_PATH" value=":base" />
- </configuration>
- </facet>
- <facet type="android" name="Android">
- <configuration>
- <option name="SELECTED_BUILD_VARIANT" value="debug" />
- <option name="ASSEMBLE_TASK_NAME" value="assembleDebug" />
- <option name="COMPILE_JAVA_TASK_NAME" value="compileDebugSources" />
- <option name="ASSEMBLE_TEST_TASK_NAME" value="assembleDebugTest" />
- <option name="SOURCE_GEN_TASK_NAME" value="generateDebugSources" />
- <option name="TEST_SOURCE_GEN_TASK_NAME" value="generateDebugTestSources" />
- <option name="ALLOW_USER_CONFIGURATION" value="false" />
- <option name="MANIFEST_FILE_RELATIVE_PATH" value="/src/main/AndroidManifest.xml" />
- <option name="RES_FOLDER_RELATIVE_PATH" value="/src/main/res" />
- <option name="RES_FOLDERS_RELATIVE_PATH" value="" />
- <option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" />
- <option name="LIBRARY_PROJECT" value="true" />
- </configuration>
- </facet>
- </component>
- <component name="NewModuleRootManager" inherit-compiler-output="false">
- <output url="file://$MODULE_DIR$/build/intermediates/classes/debug" />
- <output-test url="file://$MODULE_DIR$/build/intermediates/classes/test/debug" />
- <exclude-output />
- <content url="file://$MODULE_DIR$">
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/debug" isTestSource="false" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/debug" isTestSource="false" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/debug" isTestSource="false" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/debug" isTestSource="false" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/debug" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/debug" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/test/debug" isTestSource="true" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/test/debug" isTestSource="true" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/test/debug" isTestSource="true" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/test/debug" isTestSource="true" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/test/debug" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/test/debug" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/res" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/resources" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/assets" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/aidl" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/java" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/jni" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/rs" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/res" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/assets" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/aidl" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/rs" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/res" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/resources" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/assets" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/aidl" isTestSource="true" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/java" isTestSource="true" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/jni" isTestSource="true" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/rs" isTestSource="true" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/assets" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/bundles" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/classes" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/coverage-instrumented-classes" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dependency-cache" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex-cache" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/jacoco" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/javaResources" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/libs" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/lint" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/manifests" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/ndk" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/pre-dexed" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/proguard" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/res" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/rs" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/symbols" />
- <excludeFolder url="file://$MODULE_DIR$/build/native-libs" />
- <excludeFolder url="file://$MODULE_DIR$/build/outputs" />
- <excludeFolder url="file://$MODULE_DIR$/build/tmp" />
- </content>
- <orderEntry type="jdk" jdkName="Android API 21 Platform" jdkType="Android SDK" />
- <orderEntry type="sourceFolder" forTests="false" />
- </component>
-</module>
-
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-apply plugin: 'com.android.library'
-
-task jar(type: Jar) {
- from fileTree(dir: 'build/intermediates/classes/release')
-}
-
-android {
- compileSdkVersion 21
- buildToolsVersion "20.0.0"
- archivesBaseName = "iotivity"
-
- libraryVariants.all { variant ->
- variant.outputs.each { output ->
- def outputFile = output.outputFile
- if (outputFile != null && outputFile.name.endsWith('.aar')) {
- def fileName = "${archivesBaseName}-${TARGET_ARCH}-${outputFile.name}"
- output.outputFile = new File(outputFile.parent, fileName)
- }
- }
- }
-
- defaultConfig {
- minSdkVersion 21
- targetSdkVersion 21
- versionCode 1
- versionName "1.0"
- }
- buildTypes {
- release {
- proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
- }
- }
-
- lintOptions {
- abortOnError false
- }
-
- sourceSets {
- main {
- manifest.srcFile 'src/main/AndroidManifest.xml'
- jni.srcDirs = [] //disable automatic ndk-build call
- jniLibs.srcDir new File(buildDir, 'native-libs')
- }
- androidTest.setRoot('src/androidTest')
- }
-}
-
-
-dependencies {
- compile fileTree(dir: 'libs', include: ['*.jar'])
-
- androidTestCompile 'com.google.dexmaker:dexmaker-mockito:1.0'
- androidTestCompile 'com.google.dexmaker:dexmaker:1.0'
- androidTestCompile 'org.mockito:mockito-core:1.10.19'
-}
-
-////////////////
-////NDK Support
-////////////////
-//If using this, Android studio will fail run the following to set the environment variable for android studio:
-//launchctl setenv ANDROID_NDK_HOME
-//otherwise remove the dependsOn part and run ./gradlew buildNative from the command line
-task copyNativeLibs(type: Copy, dependsOn: 'buildNative') {
- dependsOn 'buildNative'
- from(new File('src/main/libs')) { include '**/*.so' exclude '**/libgnustl_shared.so' }
- into new File(buildDir, 'native-libs')
-}
-
-tasks.withType(JavaCompile) { compileTask -> compileTask.dependsOn copyNativeLibs }
-
-clean.dependsOn 'cleanCopyNativeLibs'
-
-tasks.withType(com.android.build.gradle.tasks.PackageApplication) {
- pkgTask ->
- pkgTask.jniFolders = new HashSet<File>()
- pkgTask.jniFolders.add(new File(buildDir, 'native-libs'))
-}
-
-task buildNative(type: Exec) {
- if (System.env.ANDROID_NDK_HOME != null) {
- //for windows use 'ndk-build.cmd'
- //def ndkBuild = new File(System.env.ANDROID_NDK_HOME, 'ndk-build.cmd')
- def ndkBuild = new File(System.env.ANDROID_NDK_HOME, 'ndk-build')
- commandLine ndkBuild, "V=1", "APP_ABI=$TARGET_ARCH", "APP_OPTIM=$RELEASE", '-C', file('src/main').absolutePath
- } else {
- println '##################'
- println 'Skipping NDK build'
- println 'Reason: ANDROID_NDK_HOME not set.'
- println '##################'
- }
-}
+++ /dev/null
-# Add project specific ProGuard rules here.
-# By default, the flags in this file are appended to flags specified
-# in C:/android/sdk/tools/proguard/proguard-android.txt
-# You can edit the include path and order by changing the proguardFiles
-# directive in build.gradle.
-#
-# For more details, see
-# http://developer.android.com/guide/developing/tools/proguard.html
-
-# Add any project specific keep options here:
-
-# If your project uses WebView with JS, uncomment the following
-# and specify the fully qualified class name to the JavaScript interface
-# class:
-#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
-# public *;
-#}
+++ /dev/null
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.example.rcsdk"
- android:versionCode="1"
- android:versionName="1.0" >
-
- <uses-sdk
- android:minSdkVersion="8"
- android:targetSdkVersion="21" />
-
-</manifest>
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2015 Samsung Electronics All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-package org.iotivity.service.resourcecontainer;
-
-import android.content.Context;
-import java.util.List;
-
-/**
- * Every resource bundle has to provide a bundle activator that can be called
- * by the resource container on bundle startup.
- */
-public abstract class BundleActivator {
- protected RcsResourceContainerBundleAPI bundleAPI;
- protected Context appContext;
-
- public BundleActivator(RcsResourceContainerBundleAPI bundleAPI, Context appContext){
- this.bundleAPI = bundleAPI;
- this.appContext = appContext;
- }
- /**
- * Activates the bundle and creates all resources.
- */
- public abstract void activateBundle();
-
- /**
- * Deactivates the bundle and destroys all resources.
- */
- public abstract void deactivateBundle();
-
- /**
- * Creates a resources
- * @param resource Instance of a BundleResource
- */
- public abstract void createResource(ResourceConfig resource);
-
- /**
- * Destroys a resource
- * @param resource Instance of a BundleResource
- */
- public abstract void destroyResource(BundleResource resource);
-
-}
\ No newline at end of file
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2015 Samsung Electronics All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-package org.iotivity.service.resourcecontainer;
-
-import java.util.HashMap;
-import java.util.Set;
-import android.content.Context;
-import android.util.Log;
-
-/**
- * Basic BundleResource that should be used as a base class by a bundle
- * resources. A concrete technology has to override the setAttribute and
- * getAttribute method and map the according reads and writes to the technology
- * specific messages.
- */
-public abstract class BundleResource {
- protected String m_name, m_uri, m_resourceType, m_address;
-
- protected RcsResourceAttributes m_attributes = new RcsResourceAttributes();
-
- protected Context m_context;
-
- long mNativeHandle;
-
- protected native void updateNativeInstance(RcsResourceAttributes update);
-
- public BundleResource() {
- initAttributes();
- }
-
- public BundleResource(Context context) {
- this();
- this.m_context = context;
- }
-
- /**
- * Initialize the internal attribute structure.
- */
- protected abstract void initAttributes();
-
- /**
- * Set the attribute (map to a send command for the according protocol)
- *
- * @param key
- * name of the attribute to be set
- * @param value
- * new value of the attribute
- */
- protected final void setAttribute(String key, RcsValue value, boolean notify) {
- m_attributes.put(key, value);
-
- if(notify){
- updateNativeInstance(m_attributes);
- }
- }
-
- /**
- * Set the attribute (map to a send command for the according protocol)
- *
- * @param key
- * name of the attribute to be set
- * @param value
- * new value of the attribute
- */
- protected final void setAttribute(String key, RcsValue value) {
- setAttribute(key, value, false);
- }
-
- /**
- * Set the attribute (map to a send command for the according protocol)
- *
- * @param key
- * name of the attribute to be set
- * @param value
- * new value of the attribute
- */
- protected final void setAttributes(RcsResourceAttributes value, boolean notify) {
- m_attributes.put(value);
-
- if(notify){
- updateNativeInstance(m_attributes);
- }
- }
-
- protected final void setAttributes(RcsResourceAttributes value) {
- setAttributes(value, false);
- }
-
- /**
- * Set the attribute (map to a send command for the according protocol)
- *
- * @param key
- * name of the attribute to be set
- * @param value
- * new value of the attribute
- */
- public abstract void handleSetAttributesRequest(RcsResourceAttributes value);
-
- /**
- * Deactivates the resource
- */
- public abstract void deactivateResource();
-
- /**
- * Retrieve the attribute (only data)
- *
- * @param key
- * name of the attribute to be read
- * @return Value of the attribute
- */
- protected final RcsValue getAttribute(String key) {
- return m_attributes.get(key);
- }
-
- protected final RcsResourceAttributes getAttributes() {
- RcsResourceAttributes ret = new RcsResourceAttributes(this.m_attributes);
- return ret;
- }
-
- /**
- * Retrieve the attribute (map to read command)
- *
- * @param key
- * name of the attribute to be set
- * @param value
- * new value of the attribute
- */
- public abstract RcsResourceAttributes handleGetAttributesRequest();
-
- /**
- * Attribute keys provided through by the bundle resource.
- *
- * @return Name of attribute keys as string array
- */
- public String[] getAttributeKeys() {
- Set<String> keys = m_attributes.keySet();
- return keys.toArray(new String[keys.size()]);
- }
-
- /**
- * Setter for the uri property
- *
- * @param uri
- * URI of the resource
- */
- public void setURI(String uri) {
- this.m_uri = uri;
- }
-
- /**
- * Returns the URI of the resource
- *
- * @return Resource URI
- */
- public String getURI() {
- return m_uri;
- }
-
- /**
- * Sets the resource type property
- *
- * @param resourceType
- * OIC resource type
- */
- public void setResourceType(String resourceType) {
- this.m_resourceType = resourceType;
- }
-
- /**
- * Getter for the resource type
- *
- * @return OIC resource type
- */
- public String getResourceType() {
- return m_resourceType;
- }
-
- /**
- * Sets the technology specific address information (e.g., ZigBee short or
- * long identifier)
- *
- * @param address
- * Resource address
- */
- public void setAddress(String address) {
- this.m_address = address;
- }
-
- /**
- * Returns the technology specific address information
- *
- * @return Resource address
- */
- public String getAddress() {
- return m_address;
- }
-
- /**
- * Sets the name property of the resource
- *
- * @param name
- * Resource name
- */
- public void setName(String name) {
- this.m_name = name;
- }
-
- /**
- * Returns the name property of the resource
- *
- * @return Resource name
- */
- public String getName() {
- return m_name;
- }
-}
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2015 Samsung Electronics All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-
-package org.iotivity.service.resourcecontainer;
-
-import java.util.HashMap;
-import java.util.Set;
-import java.util.Vector;
-import android.content.Context;
-import android.util.Log;
-
-/**
- * Every resource bundle has to provide a bundle activator that can be called
- * by the resource container on bundle startup.
- */
-public abstract class BundleSoftSensorResource extends BundleResource {
- protected HashMap<String, RcsValue> m_mapInputData;
-
- public BundleSoftSensorResource(Context context) {
- super(context);
- }
- /**
- * Initialize the internal attribute structure.
- */
- protected abstract void onUpdatedInputResource(String attributeName, Vector<RcsValue> values);
-
- /**
- * SoftSensor logic. Has to be provided by the soft sensor developer.
- * This function will be executed if an input attribute is updated.
- *
- * @return void
- */
- protected abstract void executeLogic();
-}
\ No newline at end of file
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2015 Samsung Electronics All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-
-/**
- * @file
- * This file contains RCSBundleInfo class, which provides APIs related to Bundle information.
- */
-package org.iotivity.service.resourcecontainer;
-
-/**
- * This class provides APIs for getting and setting the Bundle Information
- */
-public class RcsBundleInfo {
- private final String mId;
- private final String mPath;
- private final String mActivatorName;
- private final String mLibraryPath;
- private final String mVersion;
- private boolean mActivated; // not final since it might be modified for Android-specific bundles
-
- private RcsBundleInfo(String id, String path, String activatorName,
- String libraryPath, String version) {
- mId = id;
- mPath = path;
- mActivatorName = activatorName;
- mLibraryPath = libraryPath;
- mVersion = version;
- mActivated = false;
- }
-
- private RcsBundleInfo(String id, String path, String activatorName,
- String libraryPath, String version, boolean activated) {
- mId = id;
- mPath = path;
- mActivatorName = activatorName;
- mLibraryPath = libraryPath;
- mVersion = version;
- mActivated = activated;
- }
-
- /**
- * API for getting the Id of the bundle
- *
- * @return string - Id of the bundle
- *
- */
- public String getID() {
- return mId;
- }
-
- /**
- * API for getting the path of the bundle
- *
- * @return path - path of the bundle
- *
- */
- public String getPath() {
- return mPath;
- }
-
- /**
- * API for setting the Activator name for the bundle
- *
- * @return string - Name of the activator
- *
- */
- public String getActivatorName() {
- return mActivatorName;
- }
-
- /**
- * API for getting the version of the bundle
- *
- * @return string - version of the bundle
- *
- */
- public String getVersion() {
- return mVersion;
- }
-
- /**
- * Returns the current activation status of the bundle
- *
- * @return boolean - bundle has been successfully loaded and started
- *
- */
- public boolean isActivated() {
- return mActivated;
- }
-
- /**
- * Set the current activation status of the bundle
- *
- * @return boolean - bundle has been successfully loaded and started
- *
- */
- protected void setActivated(boolean activated) {
- mActivated = activated;
- }
-}
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2015 Samsung Electronics All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-
-package org.iotivity.service.resourcecontainer;
-
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-
-/**
- *
- * This class represents the attributes for a resource.
- *
- * @see RcsValue
- */
-public final class RcsResourceAttributes
-{
-
- private final Map<String, RcsValue> mCache = new HashMap<>();
-
- public RcsResourceAttributes() {
- }
-
- public RcsResourceAttributes(RcsResourceAttributes attrs){
- for (final String key : attrs.keySet()) {
- mCache.put(key, attrs.get(key));
- }
- }
-
- /**
- * Returns a unmodifiable Set view of the keys contained in this attributes.
- *
- * @return an unmodifiable set view of the keys in this attributes
- */
- public Set<String> keySet() {
- return Collections.unmodifiableSet(mCache.keySet());
- }
-
- /**
- * Returns the value to which the specified key is mapped, or null if this
- * contains no mapping for the key.
- *
- * @param key
- * the key whose associated value is to be returned
- *
- * @return the value to which the specified key is mapped, or null if this
- * contains no mapping for the key
- *
- * @throws NullPointerException
- * if key is null
- */
- public RcsValue get(String key) {
- if (key == null) throw new NullPointerException("key is null");
-
- return mCache.get(key);
- }
-
- /**
- * Sets the specified value with the specified key.
- * If the object previously contained a mapping for the key, the old value
- * is replaced by the specified value.
- *
- * @param key
- * key with which the specified value is to be associated
- *
- * @param value
- * value to be associated with the specified key
- *
- * @throws NullPointerException
- * if key or value is null
- *
- */
- public void put(String key, RcsValue value) {
- if (key == null) throw new NullPointerException("key is null");
- if (value == null) throw new NullPointerException("value is null");
-
- mCache.put(key, value);
- }
-
- /**
- * Sets the specified value with the specified key.
- * If the object previously contained a mapping for the key, the old value
- * is replaced by the specified value.
- *
- * @param key
- * key with which the specified value is to be associated
- *
- * @param value
- * value to be associated with the specified key
- *
- * @throws NullPointerException
- * if key or value is null
- * @throws IllegalArgumentException
- * if object is not supported type by {@link RcsValue}
- */
- public void put(String key, Object object) {
- if (key == null) throw new NullPointerException("key is null");
-
- put(key, new RcsValue(object));
- }
-
- /**
- * Returns true if this contains no key-value mappings.
- *
- * @return true if this contains no key-value mappings
- */
- public boolean isEmpty() {
- return mCache.isEmpty();
- }
-
- /**
- * Returns the number of key-value mappings.
- *
- * @return the number of key-value mappings
- */
- public int size() {
- return mCache.size();
- }
-
- /**
- * Removes the mapping for a key from this attributes if it is present.
- *
- * @param key
- * key whose mapping is to be removed
- *
- * @return true if the key is present and the the value mapped is removed.
- */
- public boolean remove(String key) {
- if (key == null) throw new NullPointerException("key is null");
-
- final boolean cacheRemove = mCache.remove(key) != null;
-
- return cacheRemove;
- }
-
- /**
- * Removes all of the mappings.
- */
- public void clear(){
- mCache.clear();
- }
-
- /**
- * Returns true if this contains a mapping for the specified key.
- *
- * @param key
- * key whose presence is to be tested
- *
- * @return true if this contains a mapping for the specified key.
- *
- * @throws NullPointerException
- * if key is null
- */
- public boolean contains(String key) {
- if (key == null) throw new NullPointerException("key is null");
-
- return mCache.containsKey(key);
- }
-
-
- @Override
- public boolean equals(Object o) {
- if (o == this) return true;
- if (!(o instanceof RcsResourceAttributes)) return false;
- RcsResourceAttributes rhs = (RcsResourceAttributes) o;
- return mCache.equals(rhs.mCache);
- }
-
- @Override
- public int hashCode() {
- return mCache.hashCode();
- }
-
- /**
- * Updates all properties provided as parameter.
- */
- public void put(RcsResourceAttributes attrs){
- for (final String key : attrs.keySet()) {
- mCache.put(key, attrs.get(key));
- }
- }
-}
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2015 Samsung Electronics All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-
-/**
- * @file
- * This file contains the Resource Container APIs
- */
-package org.iotivity.service.resourcecontainer;
-
-import java.util.List;
-
-import java.util.Map;
-import java.util.Enumeration;
-import android.util.Log;
-import android.content.Context;
-import java.util.Vector;
-
-import dalvik.system.DexFile;
-import android.content.pm.ApplicationInfo;
-import android.content.pm.PackageManager;
-import dalvik.system.PathClassLoader;
-import java.net.URLClassLoader;
-
-import java.util.Hashtable;
-import java.io.File;
-import java.net.URL;
-
-import java.lang.reflect.InvocationTargetException;
-
-/**
- * This class provides APIs for managing the container and bundles in the
- * container.
- */
-public class RcsResourceContainer implements RcsResourceContainerBundleAPI {
-
- private static final String TAG = RcsResourceContainer.class.getSimpleName();
-
- static {
- System.loadLibrary("gnustl_shared");
- System.loadLibrary("oc_logger");
- System.loadLibrary("connectivity_abstraction");
- System.loadLibrary("ca-interface");
- System.loadLibrary("octbstack");
- System.loadLibrary("oc");
- System.loadLibrary("rcs_client");
- System.loadLibrary("rcs_server");
- System.loadLibrary("rcs_common");
- System.loadLibrary("rcs_container");
- System.loadLibrary("resource_container_jni");
- }
-
- private Context appContext;
-
- private native void nativeStartContainer(String configFile);
-
- private native void nativeStopContainer();
-
- private native void nativeAddBundle(String bundleId, String bundleUri,
- String bundlePath, String activator, Map<String, String> params);
-
- private native void nativeRemoveBundle(String bundleId);
-
- private native List<RcsBundleInfo> nativeListBundles();
-
- private native void nativeStartBundle(String bundleId);
-
- private native void nativeStopBundle(String bundleId);
-
- private native void nativeAddResourceConfig(String bundleId,
- String resourceUri, Map<String, String> params);
-
- private native void nativeRemoveResourceConfig(String bundleId,
- String resourceUri);
-
- private native List<String> nativeListBundleResources(String bundleId);
-
- private native void nativeRegisterBundleResource(BundleResource resource,
- String[] attributes, String bundleId, String uri,
- String resourceType, String name);
-
- private native void nativeUnregisterBundleResource(BundleResource resource,
- String uri);
-
- private native int nativeGetNumberOfConfiguredResources(String bundleId);
-
- private native String[] nativeGetConfiguredResourceParams(String bundleId,
- int resId);
-
- public RcsResourceContainer(Context appContext){
- this.appContext = appContext;
- }
-
- private Hashtable<String, BundleActivator> activators = new Hashtable<String, BundleActivator>();
-
- /**
- * API for starting the Container
- *
- * <p>
- * This API start the container with the provided Configuration file.
- *
- * @param configFile
- * configuration File that contains the Bundle/Bundles
- * information.
- *
- */
- public List<RcsBundleInfo> startContainer(String configFile) {
- if(configFile == null || configFile.isEmpty()){
- throw new IllegalArgumentException(
- "Configuration file is null or empty.");
- }
- nativeStartContainer(configFile);
- Log.d(TAG, "startContainer in Java");
- List<RcsBundleInfo> bundles = listBundles();
- Log.d(TAG, "startContainer. There are " + bundles.size() + " bundles.");
- for(RcsBundleInfo bundleInfo : bundles){
- Log.d(TAG, "bundle-id: " + bundleInfo.getID() + ", " + bundleInfo.getPath());
- if(bundleInfo.getPath().endsWith(".apk")){ // load classes from standalone application
- startBundleFromStandaloneApp(bundleInfo);
- }else if(bundleInfo.getPath().endsWith(".jar")){ // load classes from library
- startBundleFromJar(bundleInfo);
- }
- }
- return bundles;
- }
-
- private void startBundleFromStandaloneApp(RcsBundleInfo bundleInfo){
- if(bundleInfo == null){
- throw new IllegalArgumentException(
- "bundleInfo parameter is null or empty.");
- }
- String packageName = bundleInfo.getPath().replace(".apk", "");
- try{
- PackageManager packageManager = appContext.getPackageManager();
- ApplicationInfo appInfo = packageManager.getApplicationInfo(packageName, 0);
- DexFile df = new DexFile(appInfo.sourceDir);
- ClassLoader cl = appContext.getClassLoader();
- for (Enumeration<String> iter = df.entries(); iter.hasMoreElements(); ) {
- String classN = iter.nextElement();
- if (classN.contains(packageName)) {
- Log.d(TAG,"Class: " + classN);
- df.loadClass(classN, cl);
- }
- }
- String className = bundleInfo.getActivatorName();
- Log.d(TAG, "Loading activator: " + className);
- Class activatorClass = df.loadClass(className, cl);
- activateBundle(activatorClass, bundleInfo);
- }
- catch(Exception e){
- Log.e(TAG, e.getMessage(), e);
- }
- Log.d(TAG, "Have to register android bundle");
- }
-
- private void startBundleFromJar(RcsBundleInfo bundleInfo){
- if(bundleInfo == null){
- throw new IllegalArgumentException(
- "bundleInfo parameter is null");
- }
- try{
- Log.e(TAG, "Loading from .jar file.");
-
- PathClassLoader classLoader = new PathClassLoader(bundleInfo.getPath(),
- RcsResourceContainer.class.getClassLoader());
-
- String className = bundleInfo.getActivatorName().replace('/', '.');
- Log.d(TAG, "Loading activator: " + className);
- Class activatorClass = Class.forName(className, true, classLoader);
-
- activateBundle(activatorClass, bundleInfo);
- }
- catch(Exception e){
- Log.e(TAG, e.getMessage(), e);
- }
- Log.d(TAG, "Have to register android bundle");
- }
-
- private void activateBundle(Class activatorClass, RcsBundleInfo bundleInfo) throws
- NoSuchMethodException, InstantiationException, IllegalAccessException,
- InvocationTargetException{
- if(activatorClass == null){
- throw new IllegalArgumentException(
- "activatorClass is null.");
- }
- if(bundleInfo == null){
- throw new IllegalArgumentException(
- "bundleInfo is null.");
- }
- if(activatorClass!= null){
- BundleActivator activator = (BundleActivator) activatorClass.
- getConstructor(RcsResourceContainerBundleAPI.class, Context.class).
- newInstance(this, appContext);
- activator.activateBundle();
- activators.put(bundleInfo.getID(), activator);
- bundleInfo.setActivated(true);
- }else{
- Log.e(TAG, "Activator is null.");
- }
- }
-
- /**
- * API for stopping the Container
- */
- public void stopContainer() {
- // stop all android bundles
- for(BundleActivator activator :activators.values()){
- activator.deactivateBundle();
- }
- nativeStopContainer();
- }
-
- /**
- * API for getting the list of all bundles in the container
- *
- * @return list<RCSBundleInfo> -List of BundleInfo objects each associated
- * with a bundle
- *
- * {@link RcsBundleInfo}
- */
- public List<RcsBundleInfo> listBundles() {
- return nativeListBundles();
- }
-
- /**
- * API for adding the bundle to the Container
- *
- * @param bundleId
- * Id of the Bundle
- * @param bundleUri
- * Uri of the bundle
- * @param bundlePath
- * Path of the bundle
- * @param activator
- * Activation prefix for .so bundles, or activator class name for
- * .jar bundles
- * @param params
- * key-value pairs in string form for other Bundle parameters
- *
- * <p>
- * It is dynamic configuration
- */
- public void addBundle(String bundleId, String bundleUri, String bundlePath,
- String activator, Map<String, String> params) {
- if(bundleId == null){
- throw new IllegalArgumentException(
- "bundleId parameter is null.");
- }
- if(bundleUri == null){
- throw new IllegalArgumentException(
- "bundleUri is null.");
- }
- if(bundlePath == null){
- throw new IllegalArgumentException(
- "bundlePath is null.");
- }
- if(activator == null){
- throw new IllegalArgumentException(
- "activator is null.");
- }
- nativeAddBundle(bundleId, bundleUri, bundlePath, activator, params);
- }
-
- /**
- * API for removing the bundle from the container
- *
- * @param bundleId
- * Id of the Bundle
- *
- */
- public void removeBundle(String bundleId) {
- if(bundleId == null || bundleId.isEmpty()){
- throw new IllegalArgumentException(
- "bundleId parameter is null or empty.");
- }
- if(activators.contains(bundleId)){
- // deactivate android bundle
- activators.get(bundleId).deactivateBundle();
- }
- nativeRemoveBundle(bundleId);
- }
-
- /**
- * API for starting the bundle.
- *
- * @param bundleId
- * Id of the Bundle
- *
- */
- public void startBundle(String bundleId) {
- Log.d(TAG, "startBundle");
- if(bundleId == null || bundleId.isEmpty()){
- throw new IllegalArgumentException(
- "bundleId parameter is null or empty.");
- }
- List<RcsBundleInfo> bundles = listBundles();
-
- for(RcsBundleInfo bundleInfo : bundles){
- if(bundleInfo.getID().equals(bundleId) && bundleInfo.getPath().endsWith(".apk")){
- Log.d(TAG, "Have to start android bundle");
- Log.d(TAG, "bundle-id: " + bundleInfo.getID() + ", " + bundleInfo.getPath());
- if(bundleInfo.getPath().endsWith(".apk")){
- startBundleFromStandaloneApp(bundleInfo);
- }else if(bundleInfo.getID().equals(bundleId) &&
- bundleInfo.getPath().endsWith(".jar")){ // load classes from library
- startBundleFromJar(bundleInfo);
- }
- }else{
- nativeStartBundle(bundleId);
- }
- }
- }
-
- /**
- * API for Stopping the bundle
- *
- * @param bundleId
- * Id of the Bundle
- *
- */
- public void stopBundle(String bundleId){
- if(bundleId == null || bundleId.isEmpty()){
- throw new IllegalArgumentException(
- "bundleId parameter is null or empty.");
- }
- nativeStopBundle(bundleId);
- }
-
- /**
- * API for adding the Resource configuration information to the bundle
- *
- * @param bundleId
- * Id of the Bundle
- * @param resourceUri
- * URI of the resource
- * @param params
- * key-value pairs in string form for other Bundle parameters
- *
- */
- public void addResourceConfig(String bundleId, String resourceUri,
- Map<String, String> params) {
- if(bundleId == null || bundleId.isEmpty()){
- throw new IllegalArgumentException(
- "bundleId parameter is null or empty.");
- }
- if(resourceUri == null || resourceUri.isEmpty()){
- throw new IllegalArgumentException(
- "resourceUri parameter is null or empty.");
- }
- nativeAddResourceConfig(bundleId, resourceUri, params);
- }
-
- /**
- * API for removing the Resource configuration information from the bundle
- *
- * @param bundleId
- * Id of the Bundle
- * @param resourceUri
- * URI of the resource
- *
- */
- public void removeResourceConfig(String bundleId, String resourceUri) {
- if(bundleId == null || bundleId.isEmpty()){
- throw new IllegalArgumentException(
- "bundleId parameter is null or empty.");
- }
- if(resourceUri == null || resourceUri.isEmpty()){
- throw new IllegalArgumentException(
- "resourceUri parameter is null or empty.");
- }
- nativeRemoveResourceConfig(bundleId, resourceUri);
- }
-
- /**
- * API for getting the list of Bundle Resources
- *
- * @param bundleId
- * Id of the Bundle
- *
- * @return List<String> All the bundle resources
- */
- public List<String> listBundleResources(String bundleId) {
- if(bundleId == null || bundleId.isEmpty()){
- throw new IllegalArgumentException(
- "bundleId parameter is null or empty.");
- }
- return nativeListBundleResources(bundleId);
- }
-
- /**
- * Registers a bundle resource
- *
- * @param bundleId
- * Id of the Bundle
- * @param resource
- * resource to be registered
- */
- public void registerResource(String bundleId, BundleResource resource){
- Log.d(TAG, "register Resource");
- // bundleResources.add(resource);
-
- if(bundleId == null || bundleId.isEmpty()){
- throw new IllegalArgumentException(
- "bundleId parameter is null or empty.");
- }
- if(resource == null){
- throw new IllegalArgumentException(
- "resource parameter is null.");
- }
- nativeRegisterBundleResource(resource, resource.getAttributeKeys(), bundleId,
- resource.getURI(), resource.getResourceType(),
- resource.getName());
- }
-
- /**
- * Returns the bundle configuration for the resources
- *
- * @param bundleId
- * Id of the Bundle
- *
- * @return List<ResourceConfig> All the resource configurations for the given bundle
- */
- public List<ResourceConfig> getConfiguredBundleResources(String bundleId) {
- Log.d(TAG, "getConfiguredBundleResource " + bundleId);
- Vector<ResourceConfig> configs = new Vector<ResourceConfig>();
- if(bundleId == null || bundleId.isEmpty()){
- throw new IllegalArgumentException(
- "bundleId parameter is null or empty.");
- }
- int configuredResources = getNumberOfConfiguredResources(bundleId);
- Log.d(TAG, "configured resources " + configuredResources);
-
- for (int i = 0; i < configuredResources; i++) {
- String[] resourceParams = getConfiguredResourceParams(bundleId, i);
- ResourceConfig config = new ResourceConfig(resourceParams);
- configs.add(config);
- }
- return configs;
- }
-
- /**
- * Unregisters a bundle resource
- *
- * @param resource
- * Resource to be unregistered
- */
- public void unregisterResource(BundleResource resource){
- Log.d(TAG, "unregister Resource");
- if(resource == null){
- throw new IllegalArgumentException(
- "resource is null.");
- }
- nativeUnregisterBundleResource(resource, resource.getURI());
- }
-
- /**
- * Returns the number of configured resources
- *
- * @param bundleId
- * Id of the Bundle
- * @return number of configured resources
- */
- public int getNumberOfConfiguredResources(String bundleId){
- Log.d(TAG, "getNumberOfConfiguredResources");
- if(bundleId == null || bundleId.isEmpty()){
- throw new IllegalArgumentException(
- "bundleId parameter is null or empty.");
- }
- return nativeGetNumberOfConfiguredResources(bundleId);
- }
-
- /**
- * Provides the configured resource parameter
- *
- * @param bundleId
- * Id of the Bundle
- * @param resId
- Continuous numeric identifier within the bundle
- * @return resource paramaters such as URI, resource type, name, etc. for the resource
- */
- public String[] getConfiguredResourceParams(String bundleId, int resId){
- Log.d(TAG, "getConfiguredResourceParams");
- if(bundleId == null || bundleId.isEmpty()){
- throw new IllegalArgumentException(
- "bundleId parameter is null or empty.");
- }
- if(resId < 0){
- throw new IllegalArgumentException(
- "resId paramater has to be non-negative.");
- }
- return nativeGetConfiguredResourceParams(bundleId, resId);
- }
-}
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2015 Samsung Electronics All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-
-/**
- * @file
- * This file contains the Resource Container APIs
- */
-package org.iotivity.service.resourcecontainer;
-
-import java.util.List;
-import java.util.Map;
-import java.util.Vector;
-
-/**
- * This class provides APIs for managing the container and bundles in the
- * container. The container provides such an interface to the bundle developer
- * to access the configuration and to register/unregister resources.
- */
-public interface RcsResourceContainerBundleAPI{
-
- public void registerResource(String bundleId, BundleResource resource);
-
- public void unregisterResource(BundleResource resource);
-
- public List<ResourceConfig> getConfiguredBundleResources(String bundleId);
-}
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2015 Samsung Electronics All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-package org.iotivity.service.resourcecontainer;
-
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * Value holds a value among various types at a time.
- *
- * Type helps identify type information of Value.
- *
- * @see RcsResourceAttributes
- * @see Type
- */
-public final class RcsValue {
-
- private static class NullType {
- @Override
- public String toString() {
- return "";
- }
- }
-
- /**
- * Identifiers for types of Value.
- *
- * @see Type
- */
- public static enum TypeId {
- NULL, BOOLEAN, INTEGER, DOUBLE, STRING, ATTRIBUTES, ARRAY;
- }
-
- /**
- * A Helper class to identify types of Value.
- *
- * @see RcsResourceAttributes
- * @see RcsValue
- * @see TypeId
- */
- public static class Type {
- private final TypeId mTypeId;
-
- Type(TypeId typeId) {
- mTypeId = typeId;
- }
-
- /**
- * Returns type identifier.
- *
- * @return Identifier of type
- *
- * @see #getBaseTypeId(RcsValue.Type)
- */
- public final TypeId getId() {
- return mTypeId;
- }
-
- protected TypeId getBaseTypeId() {
- return mTypeId;
- }
-
- protected int getDepth() {
- return 0;
- }
-
- /**
- * Returns the type identifier of a base type of sequence.
- *
- * For non sequence types, it is equivalent to calling {@link #getId()}.
- *
- * @return identifier of type
- *
- * @see getDepth
- * @see getId
- */
- public static TypeId getBaseTypeId(Type t) {
- return t.getBaseTypeId();
- }
-
- /**
- * Returns the depth of a type.
- *
- * The return will be zero for non sequence types.
- *
- * @see getBaseTypeId
- */
- public static int getDepth(Type t) {
- return t.getDepth();
- }
-
- /**
- * Factory method to create Type instance from an object.
- * Note that object must be a supported type by RcsValue.
- *
- * @return An instance that has TypeId for obj.
- *
- * @throws NullPointerException
- * if obj is null.
- * @throws IllegalArgumentException
- * if obj is not supported type.
- *
- */
- public static Type typeOf(Object obj) {
- if (obj == null) {
- throw new NullPointerException("object is null");
- }
-
- return typeOf(obj.getClass());
- }
-
- /**
- * Factory method to create Type instance from a class.
- * Note that class must be a supported type by RcsValue.
- *
- * @return An instance that has TypeId for class.
- *
- * @throws NullPointerException
- * if cls is null.
- * @throws IllegalArgumentException
- * if cls is not supported type.
- *
- */
- public static Type typeOf(Class<?> cls) {
- if (cls == null) {
- throw new NullPointerException("class is null");
- }
-
- if (sTypes.containsKey(cls)) return sTypes.get(cls);
-
- throw new IllegalArgumentException(
- cls.getSimpleName() + " is not supported type.");
- }
- }
-
- private static class ArrayType extends Type {
- private final TypeId mBaseTypeId;
- private final int mDimension;
-
- ArrayType(TypeId baseTypeId, int dimension) {
- super(TypeId.ARRAY);
-
- mBaseTypeId = baseTypeId;
- mDimension = dimension;
- }
-
- @Override
- protected TypeId getBaseTypeId() {
- return mBaseTypeId;
- }
-
- @Override
- protected int getDepth() {
- return mDimension;
- }
- }
-
- private static final NullType sNullValue = new NullType();
-
- private static Map<Class<?>, Type> sTypes;
-
- private final Object mObject;
- private Type mType;
-
- static {
- final Map<Class<?>, Type> types = new HashMap<Class<?>, Type>();
-
- types.put(NullType.class, new Type(TypeId.NULL));
- types.put(Boolean.class, new Type(TypeId.BOOLEAN));
- types.put(Integer.class, new Type(TypeId.INTEGER));
- types.put(Double.class, new Type(TypeId.DOUBLE));
- types.put(String.class, new Type(TypeId.STRING));
- types.put(RcsResourceAttributes.class, new Type(TypeId.ATTRIBUTES));
-
- types.put(boolean[].class, new ArrayType(TypeId.BOOLEAN, 1));
- types.put(int[].class, new ArrayType(TypeId.INTEGER, 1));
- types.put(double[].class, new ArrayType(TypeId.DOUBLE, 1));
- types.put(String[].class, new ArrayType(TypeId.STRING, 1));
- types.put(RcsResourceAttributes[].class,
- new ArrayType(TypeId.ATTRIBUTES, 1));
-
- types.put(boolean[][].class, new ArrayType(TypeId.BOOLEAN, 2));
- types.put(int[][].class, new ArrayType(TypeId.INTEGER, 2));
- types.put(double[][].class, new ArrayType(TypeId.DOUBLE, 2));
- types.put(String[][].class, new ArrayType(TypeId.STRING, 2));
- types.put(RcsResourceAttributes[][].class,
- new ArrayType(TypeId.ATTRIBUTES, 2));
-
- types.put(boolean[][][].class, new ArrayType(TypeId.BOOLEAN, 3));
- types.put(int[][][].class, new ArrayType(TypeId.INTEGER, 3));
- types.put(double[][][].class, new ArrayType(TypeId.DOUBLE, 3));
- types.put(String[][][].class, new ArrayType(TypeId.STRING, 3));
- types.put(RcsResourceAttributes[][][].class,
- new ArrayType(TypeId.ATTRIBUTES, 3));
-
- sTypes = Collections.unmodifiableMap(types);
-
- }
-
- static boolean isSupportedType(Class<?> cls) {
- return sTypes.containsKey(cls);
- }
-
- static void verifySupportedType(Class<?> cls) {
- if (!isSupportedType(cls)) {
- throw new IllegalArgumentException(
- cls.getSimpleName() + " is not supported type.");
- }
- }
-
- /**
- * Constructs a new value with an object.
- *
- * @param value
- * An object
- *
- * @throws NullPointerException
- * if value is null.
- * @throws IllegalArgumentException
- * if value is not supported type.
- */
- public RcsValue(Object value) {
- if (value == null) throw new NullPointerException("value is null!");
-
- verifySupportedType(value.getClass());
-
- mObject = value;
- }
-
- /**
- * Constructs a new value that holds null value.
- *
- */
- public RcsValue() {
- this(sNullValue);
- }
-
- /**
- * Constructs a new value that holds a boolean value.
- *
- * @param value
- * a boolean
- */
- public RcsValue(boolean value) {
- this((Object) value);
- }
-
- /**
- * Constructs a new value that holds an int value.
- *
- * @param value
- * an int
- */
- public RcsValue(int value) {
- this((Object) value);
- }
-
- /**
- * Constructs a new value that holds a double value.
- *
- * @param value
- * a double
- */
- public RcsValue(double value) {
- this((Object) value);
- }
-
- /**
- * Constructs a new value that holds a String value.
- *
- * @param value
- * a String
- *
- * @throws NullPointerException
- * if value is null.
- */
- public RcsValue(String value) {
- this((Object) value);
- }
-
- /**
- * Constructs a new value that holds a RcsResourceAttributes value.
- *
- * @param value
- * a RcsResourceAttributes
- *
- * @throws NullPointerException
- * if value is null.
- */
- public RcsValue(RcsResourceAttributes value) {
- this((Object) value);
- }
-
- /**
- * Constructs a new value that holds a boolean array.
- *
- * @param value
- * a boolean array
- *
- * @throws NullPointerException
- * if value is null.
- */
- public RcsValue(boolean[] value) {
- this((Object) value);
- }
-
- /**
- * Constructs a new value that holds a two-dimensional boolean array.
- *
- * @param value
- * a two-dimensional boolean array
- *
- * @throws NullPointerException
- * if value is null.
- */
- public RcsValue(boolean[][] value) {
- this((Object) value);
- }
-
- /**
- * Constructs a new value that holds a three-dimensional boolean array.
- *
- * @param value
- * a three-dimensional boolean array
- *
- * @throws NullPointerException
- * if value is null.
- */
- public RcsValue(boolean[][][] value) {
- this((Object) value);
- }
-
- /**
- * Constructs a new value that holds an int array.
- *
- * @param value
- * an int array
- *
- * @throws NullPointerException
- * if value is null.
- */
- public RcsValue(int[] value) {
- this((Object) value);
- }
-
- /**
- * Constructs a new value that holds a two-dimensional int array.
- *
- * @param value
- * a two-dimensional int array
- *
- * @throws NullPointerException
- * if value is null.
- */
- public RcsValue(int[][] value) {
- this((Object) value);
- }
-
- /**
- * Constructs a new value that holds a three-dimensional int array.
- *
- * @param value
- * a three-dimensional int array
- *
- * @throws NullPointerException
- * if value is null.
- */
- public RcsValue(int[][][] value) {
- this((Object) value);
- }
-
- /**
- * Constructs a new value that holds a double array.
- *
- * @param value
- * a double array
- *
- * @throws NullPointerException
- * if value is null.
- */
- public RcsValue(double[] value) {
- this((Object) value);
- }
-
- /**
- * Constructs a new value that holds a two-dimensional double array.
- *
- * @param value
- * a two-dimensional double array
- *
- * @throws NullPointerException
- * if value is null.
- */
- public RcsValue(double[][] value) {
- this((Object) value);
- }
-
- /**
- * Constructs a new value that holds a three-dimensional double array.
- *
- * @param value
- * a three-dimensional double array
- *
- * @throws NullPointerException
- * if value is null.
- */
- public RcsValue(double[][][] value) {
- this((Object) value);
- }
-
- /**
- * Constructs a new value that holds a String array.
- *
- * @param value
- * a String array
- *
- * @throws NullPointerException
- * if value is null.
- */
- public RcsValue(String[] value) {
- this((Object) value);
- }
-
- /**
- * Constructs a new value that holds a two-dimensional String array.
- *
- * @param value
- * a two-dimensional String array
- *
- * @throws NullPointerException
- * if value is null.
- */
- public RcsValue(String[][] value) {
- this((Object) value);
- }
-
- /**
- * Constructs a new value that holds a three-dimensional String array.
- *
- * @param value
- * a three-dimensional String array
- *
- * @throws NullPointerException
- * if value is null.
- */
- public RcsValue(String[][][] value) {
- this((Object) value);
- }
-
- /**
- * Constructs a new value that holds a RcsResourceAttributes array.
- *
- * @param value
- * a RcsResourceAttributes array
- *
- * @throws NullPointerException
- * if value is null.
- */
- public RcsValue(RcsResourceAttributes[] value) {
- this((Object) value);
- }
-
- /**
- * Constructs a new value that holds a two-dimensional RcsResourceAttributes
- * array.
- *
- * @param value
- * a two-dimensional RcsResourceAttributes array
- *
- * @throws NullPointerException
- * if value is null.
- */
- public RcsValue(RcsResourceAttributes[][] value) {
- this((Object) value);
- }
-
- /**
- * Constructs a new value that holds a three-dimensional
- * RcsResourceAttributes array.
- *
- * @param value
- * a three-dimensional RcsResourceAttributes array
- *
- * @throws NullPointerException
- * if value is null.
- */
- public RcsValue(RcsResourceAttributes[][][] value) {
- this((Object) value);
- }
-
- /**
- * Returns whether the value is null.
- *
- * @return true if the value is null.
- */
- public boolean isNull() {
- return isNullObject(mObject);
- }
-
- /**
- * Returns whether the object represents null for RcsValue.
- *
- * @param o
- * an object to be tested
- *
- * @return true if the object represents null.
- */
- public static boolean isNullObject(Object o) {
- return o == sNullValue;
- }
-
- /**
- * Returns type information.
- *
- * @return type information for the value.
- */
- public Type getType() {
- if (mType == null) mType = Type.typeOf(mObject);
- return mType;
- }
-
- /**
- * Returns the value as T.
- *
- * @return a value as T
- *
- * @throws ClassCastException
- * if the value is not of T.
- */
- @SuppressWarnings("unchecked")
- public <T> T get() {
- return (T) mObject;
- }
-
- @SuppressWarnings("unchecked")
- private <T> T getOrNull() {
- try {
- return (T) mObject;
- } catch (final ClassCastException e) {
- return null;
- }
- }
-
- /**
- * Returns the value as an Object.
- *
- * @return an Object
- */
- public Object asObject() {
- return mObject;
- }
-
- /**
- * Returns the value as a boolean, false if the value is not the desired
- * type.
- *
- * @return a boolean value
- *
- */
- public boolean asBoolean() {
- return asBoolean(false);
- }
-
- /**
- * Returns the value as a boolean.
- *
- * @param defaultValue
- * value to return if the value is not boolean.
- *
- * @return a boolean value
- *
- */
- public boolean asBoolean(boolean defaultValue) {
- try {
- return get();
- } catch (final ClassCastException e) {
- return defaultValue;
- }
- }
-
- /**
- * Returns the value as an int, 0 if the value is not the desired type.
- *
- * @return an int value
- *
- */
- public int asInt() {
- return asInt(0);
- }
-
- /**
- * Returns the value as an int.
- *
- * @param defaultValue
- * value to return if the value is not int.
- *
- * @return an int value
- *
- */
- public int asInt(int defaultValue) {
- try {
- return get();
- } catch (final ClassCastException e) {
- return defaultValue;
- }
- }
-
- /**
- * Returns the value as a double, 0 if the value is not the desired type.
- *
- * @return a double value
- *
- */
- public double asDouble() {
- return asDouble(0);
- }
-
- /**
- * Returns the value as a double.
- *
- * @param defaultValue
- * value to return if the value is not double.
- *
- * @return a double value
- *
- */
- public double asDouble(double defaultValue) {
- try {
- return get();
- } catch (final ClassCastException e) {
- return defaultValue;
- }
- }
-
- /**
- * Returns the value as a string, null if the value is not the desired type.
- *
- * @return a string value
- *
- */
- public String asString() {
- return asString(null);
- }
-
- /**
- * Returns the value as a String.
- *
- * @param defaultValue
- * value to return if the value is not String.
- *
- * @return a String value
- *
- */
- public String asString(String defaultValue) {
- try {
- return get();
- } catch (final ClassCastException e) {
- return defaultValue;
- }
- }
-
- /**
- * Returns the value as a RcsResourceAttributes,
- * null if the value is not the desired type.
- *
- * @return a RcsResourceAttributes value
- *
- */
- public RcsResourceAttributes asAttributes() {
- return getOrNull();
- }
-
- /**
- * Returns the value as a boolean array, null if the value is not the
- * desired type.
- *
- * @return a boolean array
- *
- */
- public boolean[] asBooleanArray() {
- return getOrNull();
- }
-
- /**
- * Returns the value as a two-dimensional boolean array, null if the value
- * is not the desired type.
- *
- * @return a two-dimensional boolean array
- *
- */
- public boolean[][] asBoolean2DArray() {
- return getOrNull();
- }
-
- /**
- * Returns the value as a three-dimensional boolean array, null if the value
- * is not the desired type.
- *
- * @return a three-dimensional boolean array
- *
- */
- public boolean[][][] asBoolean3DArray() {
- return getOrNull();
- }
-
- /**
- * Returns the value as an int array, null if the value is not the
- * desired type.
- *
- * @return an int array
- *
- */
- public int[] asIntArray() {
- return getOrNull();
- }
-
- /**
- * Returns the value as a two-dimensional int array, null if the value
- * is not the desired type.
- *
- * @return a two-dimensional int array
- *
- */
- public int[][] asInt2DArray() {
- return getOrNull();
- }
-
- /**
- * Returns the value as a three-dimensional int array, null if the value
- * is not the desired type.
- *
- * @return a three-dimensional int array
- *
- */
- public int[][][] asInt3DArray() {
- return getOrNull();
- }
-
- /**
- * Returns the value as a double array, null if the value is not the
- * desired type.
- *
- * @return a double array
- *
- */
- public double[] asDoubleArray() {
- return getOrNull();
- }
-
- /**
- * Returns the value as a two-dimensional double array, null if the value
- * is not the desired type.
- *
- * @return a two-dimensional double array
- *
- */
- public double[][] asDouble2DArray() {
- return getOrNull();
- }
-
- /**
- * Returns the value as a three-dimensional double array, null if the value
- * is not the desired type.
- *
- * @return a three-dimensional double array
- *
- */
- public double[][][] asDouble3DArray() {
- return getOrNull();
- }
-
- /**
- * Returns the value as a string array, null if the value is not the
- * desired type.
- *
- * @return a string array
- *
- */
- public String[] asStringArray() {
- return getOrNull();
- }
-
- /**
- * Returns the value as a two-dimensional string array, null if the value
- * is not the desired type.
- *
- * @return a two-dimensional string array
- *
- */
- public String[][] asString2DArray() {
- return getOrNull();
- }
-
- /**
- * Returns the value as a three-dimensional string array, null if the value
- * is not the desired type.
- *
- * @return a three-dimensional string array
- *
- */
- public String[][][] asString3DArray() {
- return getOrNull();
- }
-
- /**
- * Returns the value as an attributes array, null if the value is not the
- * desired type.
- *
- * @return an attributes array
- *
- */
- public RcsResourceAttributes[] asAttributesArray() {
- return getOrNull();
- }
-
- /**
- * Returns the value as a two-dimensional attributes array, null if the
- * value is not the desired type.
- *
- * @return a two-dimensional attributes array
- *
- */
- public RcsResourceAttributes[][] asAttributes2DArray() {
- return getOrNull();
- }
-
- /**
- * Returns the value as a three-dimensional attributes array, null if the
- * value is not the desired type.
- *
- * @return a three-dimensional attributes array
- *
- */
- public RcsResourceAttributes[][][] asAttributes3DArray() {
- return getOrNull();
- }
-
- @Override
- public boolean equals(Object o) {
- if (o == this) return true;
- if (!(o instanceof RcsValue)) return false;
-
- final RcsValue rhs = (RcsValue) o;
-
- return mObject.equals(rhs.mObject);
- }
-
- @Override
- public int hashCode() {
- return mObject.hashCode();
- }
-
- @Override
- public String toString() {
- return mObject.toString();
- }
-
-}
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2015 Samsung Electronics All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-package org.iotivity.service.resourcecontainer;
-
-/**
- * This class holds the configuration parameters for a single resource instance provided
- * by the resource bundle.
- */
-public class ResourceConfig {
- private String m_name, m_uri, m_resourceType, m_address;
-
- /**
- * Empty constructor for resoure config.
- */
- public ResourceConfig() {
- }
-
- /**
- * Creates a new resource config instance.
- * @param params Resource parameters as array. 1. Name, 2. URI, 3. Resource Type, 4. Address
- */
- public ResourceConfig(String[] params) {
- m_name = params[0];
- m_uri = params[1];
- m_resourceType = params[2];
- m_address = params[3];
- }
-
- /**
- * Returns the configured name
- * @return name property
- */
- public String getName() {
- return m_name;
- }
-
- /**
- * Sets the name
- * @param m_name Resource name
- */
- public void setName(String m_name) {
- this.m_name = m_name;
- }
-
- /**
- * Returns the configured URI
- * @return Configured URI
- */
- public String getURI() {
- return m_uri;
- }
-
- /**
- * Sets the configured URI
- * @param m_uri Configuration URI
- */
- public void setURI(String m_uri) {
- this.m_uri = m_uri;
- }
-
- /**
- * Returns the configured resource type
- * @return configured resource type
- */
- public String getResourceType() {
- return m_resourceType;
- }
-
- /**
- * Sets the configured resource type
- * @param m_resourceType updates the configured resource type
- */
- public void setResourceType(String m_resourceType) {
- this.m_resourceType = m_resourceType;
- }
-
- /**
- * Returns the configured address
- * @return Configured address
- */
- public String getAddress() {
- return m_address;
- }
-
- /**
- * Sets the configured address
- * @param m_address Configured address
- */
- public void setAddress(String m_address) {
- this.m_address = m_address;
- }
-
- @Override
- public String toString() {
- return "ResourceConfig [m_name=" + m_name + ", m_uri=" + m_uri
- + ", m_resourceType=" + m_resourceType + ", m_address="
- + m_address + "]";
- }
-
-}
+++ /dev/null
-LOCAL_PATH := $(call my-dir)
-
-ROOT_PATH := ../../../../../../..
-IOTIVITY_LIB_PATH := $(ROOT_PATH)/out/android/$(TARGET_ARCH_ABI)/$(APP_OPTIM)
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := rcs_container
-LOCAL_SRC_FILES := $(IOTIVITY_LIB_PATH)/librcs_container.so
-include $(PREBUILT_SHARED_LIBRARY)
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := rcs_common
-LOCAL_SRC_FILES := $(IOTIVITY_LIB_PATH)/librcs_common.so
-include $(PREBUILT_SHARED_LIBRARY)
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := rcs_client
-LOCAL_SRC_FILES := $(IOTIVITY_LIB_PATH)/librcs_client.so
-include $(PREBUILT_SHARED_LIBRARY)
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := rcs_server
-LOCAL_SRC_FILES := $(IOTIVITY_LIB_PATH)/librcs_server.so
-include $(PREBUILT_SHARED_LIBRARY)
-include $(CLEAR_VARS)
-OIC_SRC_DIR := ../../../../../..
-LOCAL_MODULE := resource_container_jni
-
-LOCAL_C_INCLUDES := $(LOCAL_PATH)/util
-LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/extlibs/boost/boost_1_58_0
-LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/service/resource-container/include
-LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/service/resource-container/bundle-api/include
-LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/service/resource-container/src
-LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/service/resource-encapsulation/include
-LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/service/resource-encapsulation/src/serverBuilder/include
-LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/resource/csdk/stack/include
-LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/resource/csdk/logger/include
-LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/resource/oc_logger/include
-LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/resource/c_common
-
-LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/extlibs/
-
-LOCAL_SRC_FILES += $(patsubst $(LOCAL_PATH)/%, %, $(wildcard $(LOCAL_PATH)/util/*.cpp))
-LOCAL_SRC_FILES += $(patsubst $(LOCAL_PATH)/%, %, $(wildcard $(LOCAL_PATH)/*.cpp))
-
-LOCAL_CPPFLAGS := -std=c++0x -frtti -fexceptions
-
-
-
-LOCAL_LDLIBS := -llog
-
-LOCAL_SHARED_LIBRARIES += rcs_container rcs_common rcs_client rcs_server rcs_jni
-
-include $(BUILD_SHARED_LIBRARY)
+++ /dev/null
-NDK_TOOLCHAIN_VERSION := 4.9
-APP_STL := gnustl_shared
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2015 Samsung Electronics All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-
-#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(const RCSResourceAttributes &attrs,
- const std::map< std::string, std::string > &queryParams)
-{
- 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(const
- std::map< std::string, std::string > &queryParams)
-{
- 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");
- const 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);
-}
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2015 Samsung Electronics All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#ifndef JNI_BUNDLERESOURCE_H_
-#define JNI_BUNDLERESOURCE_H_
-
-#include <map>
-#include <vector>
-#include <string>
-#include <jni.h>
-#include "BundleResource.h"
-#include "SoftSensorResource.h"
-#include "ResourceContainerImpl.h"
-
-#include <jni.h>
-
-class JNIEnvWrapper;
-
-void initRCSJniBundleResource(JNIEnvWrapper *);
-
-using namespace std;
-
-namespace OIC
-{
- namespace Service
- {
- class JniBundleResource: public SoftSensorResource
- {
- public:
- JniBundleResource();
- JniBundleResource(JNIEnv *env, jobject obj, jobject bundleResource, string bundleId,
- jobjectArray attributes);
- virtual ~JniBundleResource();
-
- void handleSetAttributeRequest(const std::string& key,
- RCSResourceAttributes::Value&&);
-
- RCSResourceAttributes::Value handleGetAttributeRequest(const std::string& key);
-
- virtual void handleSetAttributesRequest(const RCSResourceAttributes &attrs,
- const std::map< std::string, std::string > &queryParams);
-
- virtual RCSResourceAttributes handleGetAttributesRequest(const
- std::map< std::string, std::string > &queryParams);
-
- /**
- * SoftSensor logic. Has to be provided by the soft sensor developer.
- * This function will be executed if an input attribute is updated.
- *
- * @return void
- */
- virtual void executeLogic();
-
- /**
- * Callback from the client module in the container.
- * This function will be called if input data from remote resources are updated.
- * SoftSensor resource can get a vector of input data from multiple input resources
- * which have attributeName that softsensor needs to execute its logic.
- *
- * @param attributeName Attribute key of input data
- *
- * @param values Vector of input data value
- *
- * @return void
- */
- virtual void onUpdatedInputResource(const std::string attributeName,
- std::vector<RCSResourceAttributes::Value> values);
-
- virtual void initAttributes();
- private:
- // needs to be a GlobalRef
- jobject m_bundleResource;
- jobjectArray m_attributes;
- jclass m_bundleResourceClass;
- jmethodID m_attributeSetRequestHandler;
- jmethodID m_attributeGetRequestHandler;
- jmethodID m_onUpdatedInputResource;
- 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;
- };
- }
-}
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-/*
- * Class: org_iotivity_service_resourcecontainer_JniBundleResource
- * Method: updateNativeInstance
- * Signature: (Lorg/iotivity/service/resourcecontainer/RcsResourceAttributes;)V
- */
-JNIEXPORT void JNICALL Java_org_iotivity_service_resourcecontainer_BundleResource_updateNativeInstance
- (JNIEnv *, jobject, jobject);
-
-#ifdef __cplusplus
-}
-#endif
-#endif
-
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-#include "JniRcsResourceContainer.h"
-#include "JniRcsResourceAttributes.h"
-#include "JavaClasses.h"
-#include "JNIEnvWrapper.h"
-#include "Log.h"
-#include "JniRcsValue.h"
-#include "JavaExceptions.h"
-#include "JniRcsValue.h"
-#include "JniBundleResource.h"
-
-#define LOG_TAG "JNI-Main"
-
-#define JNI_CURRENT_VERSION JNI_VERSION_1_6
-
-JavaVM *g_jvm;
-
-JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved)
-{
- LOGI("JNI_OnLoad");
- JNIEnv *env;
- g_jvm = vm;
-
- if (g_jvm->GetEnv((void **)&env, JNI_CURRENT_VERSION) != JNI_OK)
- {
- LOGE("Failed to get the environment using GetEnv()");
- return JNI_ERR;
- }
-
- JNIEnvWrapper envWrapper { env };
-
- try
- {
- initJavaClasses(&envWrapper);
- initJavaExceptions(&envWrapper);
- initRCSValue(&envWrapper);
- initRCSResourceContainer(&envWrapper);
- initRCSResourceAttributes(&envWrapper);
- initRCSJniBundleResource(&envWrapper);
- }
- catch (const JavaException &)
- {
- if (env->ExceptionCheck()) env->ExceptionDescribe();
- return JNI_ERR;
- }
-
- return JNI_CURRENT_VERSION;
-}
-
-JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *vm, void *reserved)
-{
- LOGI("JNI_OnUnload");
- JNIEnv *env;
-
- if (g_jvm->GetEnv((void **)&env, JNI_CURRENT_VERSION) != JNI_OK)
- {
- LOGE("Failed to get the environment using GetEnv()");
- return;
- }
-
- JNIEnvWrapper envWrapper { env };
-
- try
- {
- clearRCSResourceContainer(&envWrapper);
- clearJavaClasses(&envWrapper);
- }
- catch (const JavaException &)
- {
- }
-}
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-#include "JniRcsResourceAttributes.h"
-
-#include "JNIEnvWrapper.h"
-#include "JavaClasses.h"
-#include "JavaLocalRef.h"
-#include "JniRcsValue.h"
-#include "Log.h"
-#include "Verify.h"
-
-using namespace OIC::Service;
-
-#define LOG_TAG "JNI-RCSResourceAttributes"
-
-namespace
-{
- jclass g_cls_RCSResourceAttributes;
-
- jmethodID g_ctor_RCSResourceAttributes;
-
- jfieldID g_field_mCache;
-}
-
-void initRCSResourceAttributes(JNIEnvWrapper* env)
-{
- g_cls_RCSResourceAttributes = env->FindClassAsGlobalRef(CLS_NAME_RESOURCEATTRIBUTES);
- g_ctor_RCSResourceAttributes = env->GetConstructorID(g_cls_RCSResourceAttributes, "()V");
-
- g_field_mCache = env->GetFieldID(g_cls_RCSResourceAttributes, "mCache", AS_SIG(CLS_NAME_MAP));
-}
-
-void clearRCSResourceAttributes(JNIEnvWrapper* env)
-{
- env->DeleteGlobalRef(g_cls_RCSResourceAttributes);
-}
-
-jobject newAttributesObject(JNIEnv* env, const RCSResourceAttributes& attrs)
-{
- jobject obj = env->NewObject(g_cls_RCSResourceAttributes, g_ctor_RCSResourceAttributes);
- VERIFY_NO_EXC_RET_DEF(env);
-
- jobject mapObj = env->GetObjectField(obj, g_field_mCache);
-
- //EXPECT(mapObj, "Map is null.");
- for (const auto& p : attrs) {
- JavaLocalObject keyObj{ env, newStringObject(env, p.key()) };
- //VERIFY_NO_EXC(env);
-
- JavaLocalObject valueObj{ env, newRCSValueObject(env, p.value()) };
- //VERIFY_NO_EXC(env);
-
- invoke_Map_put(env, mapObj, keyObj, valueObj);
- //VERIFY_NO_EXC(env);
- }
-
- // setSafeNativeHandle< RCSResourceAttributes >(env, obj, attrs);
-
- return obj;
-}
-
-jobject newAttributesObject(JNIEnvWrapper* env, const RCSResourceAttributes& attrs)
-{
- jobject obj = env->NewObject(g_cls_RCSResourceAttributes, g_ctor_RCSResourceAttributes);
-
- jobject mapObj = env->GetObjectField(obj, g_field_mCache);
-
- //EXPECT(mapObj, "Map is null.");
- for (const auto& p : attrs) {
- JavaLocalObject keyObj{ env, newStringObject(env, p.key()) };
- //VERIFY_NO_EXC(env);
-
- JavaLocalObject valueObj{ env, newRCSValueObject(env, p.value()) };
- //VERIFY_NO_EXC(env);
-
- invoke_Map_put(env, mapObj, keyObj, valueObj);
- //VERIFY_NO_EXC(env);
- }
-
-// setSafeNativeHandle< RCSResourceAttributes >(env, obj, attrs);
-
- return obj;
-}
-
-RCSResourceAttributes toNativeAttributes(JNIEnv* env, jobject attrsObj)
-{
- EXPECT_RET(attrsObj, "attrsObj is null!", { });
-
- JNIEnvWrapper envWrapper{ env };
-
- try
- {
- return toNativeAttributes(&envWrapper, attrsObj);
- }
- catch (const JavaException&)
- {
- return {};
- }
-}
-
-RCSResourceAttributes toNativeAttributes(JNIEnvWrapper* env, jobject attrsObj)
-{
- EXPECT_RET(attrsObj, "attrsObj is null!", { });
-
- RCSResourceAttributes attrs;
-
- /*if (hasNativeHandle(env, attrsObj))
- {
- attrs = getNativeHandleAs< RCSResourceAttributes >(env, attrsObj);
- }*/
- LOGD("writeNativeAttributesFromMap");
-
- writeNativeAttributesFromMap(env,
- JavaLocalObject{ env, env->GetObjectField(attrsObj, g_field_mCache) }, attrs);
-
- return attrs;
-}
-
-void writeNativeAttributesFromMap(JNIEnv* env, jobject mapObj, RCSResourceAttributes& targetAttrs)
-{
- JNIEnvWrapper envWrapper{ env };
-
- try
- {
- return writeNativeAttributesFromMap(&envWrapper, mapObj, targetAttrs);
- }
- catch (const JavaException&)
- {
- }
-}
-
-void writeNativeAttributesFromMap(JNIEnvWrapper* env, jobject mapObj,
- RCSResourceAttributes& targetAttrs)
-{
- LOGD("in write native attributes from map");
- LOGD("invoke map entry set");
- JavaLocalObject setObj{ env, invoke_Map_entrySet(env, mapObj) };
- LOGD("invoke set iterator");
- JavaLocalObject iterObj{ env, invoke_Set_iterator(env, setObj) };
- LOGD("invoke has next");
- while (invoke_Iterator_hasNext(env, iterObj))
- {
- LOGD("invoke entry obj next");
- JavaLocalObject entryObj{ env, invoke_Iterator_next(env, iterObj) };
- LOGD("invoke key obj next");
- JavaLocalObject keyObj{ env, invoke_MapEntry_getKey(env, entryObj) };
- LOGD("invoke value obj next");
- JavaLocalObject valueObj{ env, invoke_MapEntry_getValue(env, entryObj) };
- LOGD("invoke toStdString");
- auto key = toStdString(env, static_cast< jstring >(keyObj.get()));
- LOGD("invoke toNativeAttrsvalue");
- targetAttrs[std::move(key)] = toNativeAttrsValue(env, valueObj);
- }
- LOGD("in write native attributes from map finished");
-}
-
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-#ifndef JNI_RCS_RESOURCE_ATTRIBUTES_H_
-#define JNI_RCS_RESOURCE_ATTRIBUTES_H_
-
-#include <jni.h>
-
-namespace OIC
-{
- namespace Service
- {
- class RCSResourceAttributes;
- }
-}
-
-class JNIEnvWrapper;
-
-void initRCSResourceAttributes(JNIEnvWrapper*);
-void clearRCSResourceAttributes(JNIEnvWrapper*);
-
-jobject newAttributesObject(JNIEnv*, const OIC::Service::RCSResourceAttributes&);
-jobject newAttributesObject(JNIEnvWrapper*, const OIC::Service::RCSResourceAttributes&);
-
-OIC::Service::RCSResourceAttributes toNativeAttributes(JNIEnv*, jobject);
-OIC::Service::RCSResourceAttributes toNativeAttributes(JNIEnvWrapper*, jobject);
-
-void writeNativeAttributesFromMap(JNIEnv*, jobject mapObj,
- OIC::Service::RCSResourceAttributes& targetAttrs);
-void writeNativeAttributesFromMap(JNIEnvWrapper*, jobject mapObj,
- OIC::Service::RCSResourceAttributes& targetAttrs);
-
-#endif //JNI_RCS_RESOURCE_ATTRIBUTES_H_
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-#include "JniRcsResourceContainer.h"
-
-#include "JavaClasses.h"
-#include "JavaLocalRef.h"
-#include "JNIEnvWrapper.h"
-#include "Log.h"
-#include "Verify.h"
-#include <dlfcn.h>
-
-#include "ResourceContainerBundleAPI.h"
-#include "JniBundleResource.h"
-#include "RCSResourceContainer.h"
-
-
-
-#define LOG_TAG "JNI-RCSResourceContainer"
-
-using namespace OIC::Service;
-
-#define CLS_NAME_BUNDLE_INFO "org/iotivity/service/resourcecontainer/RcsBundleInfo"
-
-std::map< string, BundleResource::Ptr > android_resources;
-
-namespace
-{
- jclass g_cls_RCSBundleInfo;
- jfieldID g_field_mNativeHandle;
-
- jmethodID g_ctor_RCSBundleInfo;
-
- std::map< std::string, std::string > convertJavaMapToParamsMap(JNIEnvWrapper *env,
- jobject mapObj)
- {
- EXPECT_RET_DEF(mapObj, "map is null");
-
- auto setObj = invoke_Map_entrySet(env, mapObj);
- auto iterObj = invoke_Set_iterator(env, setObj);
-
- std::map< std::string, std::string > ret;
-
- while (invoke_Iterator_hasNext(env, iterObj))
- {
- JavaLocalObject entryObj { env, invoke_Iterator_next(env, iterObj) };
-
- JavaLocalString keyObj { env,
- static_cast< jstring >(invoke_MapEntry_getKey(env, entryObj)) };
-
- JavaLocalString valueObj { env,
- static_cast< jstring >(invoke_MapEntry_getValue(env, entryObj)) };
-
- ret.emplace(toStdString(env, keyObj), toStdString(env, valueObj));
- }
-
- return ret;
- }
-
- jobject newBundleInfoObj(JNIEnvWrapper *env, const std::unique_ptr< RCSBundleInfo > &bundleInfo)
- {
- LOGD("new bundle info");
- __android_log_print(ANDROID_LOG_DEBUG, "CONTAINER", "newBundleInfoObj %s",bundleInfo->getActivatorName().c_str());
- JavaLocalString id{env, newStringObject(env, bundleInfo->getID()) };
- JavaLocalString path{env, newStringObject(env, bundleInfo->getPath()) };
- JavaLocalString activatorName{env, newStringObject(env, bundleInfo->getActivatorName()) };
- JavaLocalString libraryPath{env, newStringObject(env, bundleInfo->getLibraryPath()) };
- JavaLocalString version{env, newStringObject(env, bundleInfo->getVersion()) };
-
- return env->NewObject(g_cls_RCSBundleInfo, g_ctor_RCSBundleInfo,
- id.get(), path.get(), activatorName.get(), libraryPath.get(), version.get(),
- bundleInfo->isActivated());
- }
-}
-
-void initRCSResourceContainer(JNIEnvWrapper *env)
-{
- g_cls_RCSBundleInfo = env->FindClassAsGlobalRef(CLS_NAME_BUNDLE_INFO);
-
- g_ctor_RCSBundleInfo = env->GetConstructorID(g_cls_RCSBundleInfo, "("
- AS_SIG(CLS_NAME_STRING)
- AS_SIG(CLS_NAME_STRING)
- AS_SIG(CLS_NAME_STRING)
- AS_SIG(CLS_NAME_STRING)
- AS_SIG(CLS_NAME_STRING)
- ")V");
-
- auto clsJniBundleResource = env->FindClass(PACKAGE_NAME "/BundleResource");
-
- g_field_mNativeHandle = env->GetFieldID(clsJniBundleResource, "mNativeHandle", "J");
-}
-
-void clearRCSResourceContainer(JNIEnvWrapper *env)
-{
- env->DeleteGlobalRef(g_cls_RCSBundleInfo);
-}
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeStartContainer
-(JNIEnv *env, jobject, jstring configFileObj)
-{
- LOGD("nativeStartContainer");
-
- // A strange error message happens if the container is used as native library on Android
- // and further native libraries are loaded at runtime.
- const char *error;
- if ((error = dlerror()) != NULL)
- {
- __android_log_print(ANDROID_LOG_DEBUG, "JNI-RCSResourceContainer",
- "dlerror: %s.", error);
- }
-
- EXPECT(configFileObj, "ConfigFile is null.");
-
- auto configFile = toStdString(env, configFileObj);
- // std::string nativeFilePath = env->GetStringUTFChars(configFile, NULL);
- VERIFY_NO_EXC(env);
-
- RCSResourceContainer::getInstance()->startContainer(configFile);
-}
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeStopContainer(JNIEnv *env, jobject)
-{
- LOGD("nativeStopContainers");
-
- // A strange error message happens if the container is used as native library on Android
- // and further native libraries are loaded at runtime.
- const char *error;
- if ((error = dlerror()) != NULL)
- {
- __android_log_print(ANDROID_LOG_DEBUG, "JNI-RCSResourceContainer",
- "dlerror: %s.", error);
- }
-
- RCSResourceContainer::getInstance()->stopContainer();
-}
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeAddBundle
-(JNIEnv *env, jobject, jstring idObj, jstring uriObj, jstring pathObj, jstring activatorObj,
- jobject paramsObj)
-{
- LOGD("nativeAddBundle");
-
- // A strange error message happens if the container is used as native library on Android
- // and further native libraries are loaded at runtime.
- const char *error;
- if ((error = dlerror()) != NULL)
- {
- __android_log_print(ANDROID_LOG_DEBUG, "JNI-RCSResourceContainer",
- "dlerror: %s.", error);
- }
-
- EXPECT(idObj, "BundleId is null.");
- EXPECT(pathObj, "BundlePath is null.");
- EXPECT(activatorObj, "Activator is null.");
-
- JNIEnvWrapper envWrapper(env);
-
- try
- {
- LOGD("nativeAddBundle before calling native");
- RCSResourceContainer::getInstance()->addBundle(toStdString(&envWrapper, idObj),
- toStdString(&envWrapper, uriObj), toStdString(&envWrapper, pathObj),
- toStdString(&envWrapper, activatorObj),
- convertJavaMapToParamsMap(&envWrapper, paramsObj));
-
- LOGD("nativeAddBundle after calling native");
- }
- catch (const JavaException &)
- {
- LOGE("Failed to add bundle.");
- }
-}
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeRemoveBundle
-(JNIEnv *env, jobject, jstring idObj)
-{
- LOGD("nativeRemoveBundle");
-
- // A strange error message happens if the container is used as native library on Android
- // and further native libraries are loaded at runtime.
- const char *error;
- if ((error = dlerror()) != NULL)
- {
- __android_log_print(ANDROID_LOG_DEBUG, "JNI-RCSResourceContainer",
- "dlerror: %s.", error);
- }
-
- EXPECT(idObj, "BundleId is null.");
-
- auto id = toStdString(env, idObj);
- VERIFY_NO_EXC(env);
-
- RCSResourceContainer::getInstance()->removeBundle(id);
-}
-
-
-JNIEXPORT jobject JNICALL
-Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeListBundles
-(JNIEnv *env, jobject)
-{
- LOGD("nativeListBundles");
-
- // A strange error message happens if the container is used as native library on Android
- // and further native libraries are loaded at runtime.
- const char *error;
- if ((error = dlerror()) != NULL)
- {
- __android_log_print(ANDROID_LOG_DEBUG, "JNI-RCSResourceContainer",
- "dlerror: %s.", error);
- }
-
- JNIEnvWrapper envWrapper(env);
-
- try
- {
- auto listObj = newArrayList(&envWrapper);
-
- for (const auto& bundleInfo : RCSResourceContainer::getInstance()->listBundles())
- {
- JavaLocalObject bundleInfoObj{ &envWrapper, newBundleInfoObj(&envWrapper, bundleInfo) };
- invoke_Collection_add(&envWrapper, listObj, bundleInfoObj);
- }
- return listObj;
- }
- catch (const JavaException &)
- {
- LOGE("Failed to convert bundle info list.");
- }
- return nullptr;
-}
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeStartBundle
-(JNIEnv *env, jobject, jstring idObj)
-{
- LOGD("nativeStartBundle");
-
- // A strange error message happens if the container is used as native library on Android
- // and further native libraries are loaded at runtime.
- const char *error;
- if ((error = dlerror()) != NULL)
- {
- __android_log_print(ANDROID_LOG_DEBUG, "JNI-RCSResourceContainer",
- "dlerror: %s.", error);
- }
-
- EXPECT(idObj, "BundleId is null.");
-
- auto id = env->GetStringUTFChars(idObj, NULL);
- VERIFY_NO_EXC(env);
-
- RCSResourceContainer::getInstance()->startBundle(id);
-}
-JNICALL
-JNIEXPORT void
-Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeStopBundle
-(JNIEnv *env, jobject, jstring idObj)
-{
- LOGD("nativeStopBundle");
-
- // A strange error message happens if the container is used as native library on Android
- // and further native libraries are loaded at runtime.
- const char *error;
- if ((error = dlerror()) != NULL)
- {
- __android_log_print(ANDROID_LOG_DEBUG, "JNI-RCSResourceContainer",
- "dlerror: %s.", error);
- }
-
- EXPECT(idObj, "BundleId is null.");
-
- auto id = env->GetStringUTFChars(idObj, NULL);
- VERIFY_NO_EXC(env);
-
- RCSResourceContainer::getInstance()->stopBundle(id);
-}
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeAddResourceConfig
-(JNIEnv *env, jobject, jstring idObj, jstring uriObj, jobject paramsObj)
-{
- LOGD("nativeAddResourceConfig");
-
- EXPECT(idObj, "BundleId is null.");
- EXPECT(uriObj, "BundleUri is null.");
- EXPECT(paramsObj, "Params is null.");
-
- JNIEnvWrapper envWrapper(env);
-
- try
- {
- RCSResourceContainer::getInstance()->addResourceConfig(toStdString(&envWrapper, idObj),
- toStdString(&envWrapper, uriObj), convertJavaMapToParamsMap(&envWrapper, paramsObj));
- }
- catch (const JavaException &)
- {
- LOGE("Failed to add bundle.");
- }
-}
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeRemoveResourceConfig
-(JNIEnv *env, jobject, jstring idObj, jstring uriObj)
-{
- LOGD("nativeRemoveResourceConfig");
-
- EXPECT(idObj, "BundleId is null.");
- EXPECT(uriObj, "BundleUri is null.");
-
- auto id = toStdString(env, idObj);
- VERIFY_NO_EXC(env);
- auto uri = toStdString(env, uriObj);
- VERIFY_NO_EXC(env);
-
- RCSResourceContainer::getInstance()->removeResourceConfig(id, uri);
-}
-
-JNIEXPORT jobject JNICALL
-Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeListBundleResources
-(JNIEnv *env, jobject, jstring idObj)
-{
- LOGD("nativeListBundleResources");
-
- EXPECT_RET_DEF(idObj, "BundleId is null.");
-
- JNIEnvWrapper envWrapper(env);
-
- try
- {
- auto id = toStdString(&envWrapper, idObj);
-
- auto listObj = newArrayList(&envWrapper);
-
- for (const auto& s : RCSResourceContainer::getInstance()->listBundleResources(id))
- {
- JavaLocalString strObj{ &envWrapper, newStringObject(&envWrapper, s) };
-
- invoke_Collection_add(&envWrapper, listObj, strObj);
- }
-
- return listObj;
- }
- catch (const JavaException &)
- {
- LOGE("Failed to convert bundle info list.");
- }
-
- return nullptr;
-}
-
-
-JNIEXPORT void JNICALL
-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("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);
- __android_log_print(ANDROID_LOG_DEBUG, "JNI-RCSResourceContainer", "retrieved uri: %s.",
- str_uri.c_str());
- auto str_resourceType = toStdString(&envWrapper, resourceType);
- __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.");
- JniBundleResource res;
-
- BundleResource::Ptr androidResource = std::make_shared< JniBundleResource >
- (env, obj, bundleResource, str_bundle_id, attributes);
- ResourceContainerImpl *container = ResourceContainerImpl::getImplInstance();
-
- androidResource->m_uri = str_uri;
- androidResource->m_resourceType = str_resourceType;
- androidResource->m_name = str_res_name;
- androidResource->m_bundleId = str_bundle_id;
-
- // link java resource instance to c++ resource instance
- env->SetLongField(bundleResource, g_field_mNativeHandle, reinterpret_cast< jlong >(androidResource.get()));
-
- container->registerResource(androidResource);
-
- android_resources[str_uri] = androidResource;
-}
-
-/*
- * Class: org_iotivity_resourcecontainer_bundle_api_BaseActivator
- * Method: unregisterJavaResource
- * Signature: (Lorg/iotivity/resourcecontainer/bundle/api/BundleResource;)V
- */
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeUnregisterBundleResource
-(JNIEnv *env, jobject obj, jobject bundleResource, jstring uri)
-{
- (void)obj;
- (void)bundleResource;
- const char *str_uri = env->GetStringUTFChars(uri, 0);
-
- if (android_resources[str_uri] != NULL)
- {
- ResourceContainerImpl *container = ResourceContainerImpl::getImplInstance();
- container->unregisterResource(android_resources[str_uri]);
- android_resources.erase(str_uri);
- }
-}
-
-/*
- * Class: org_iotivity_resourcecontainer_bundle_api_BaseActivator
- * Method: getNumberOfConfiguredResources
- * Signature: (Ljava/lang/String;)I
- */
-JNIEXPORT jint JNICALL
-Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeGetNumberOfConfiguredResources(
- JNIEnv *env, jobject obj, jstring bundleId)
-{
- (void)obj;
- LOGD("nativeGetNumberOfConfiguredResources");
- const char *str_bundleId = env->GetStringUTFChars(bundleId, 0);
- LOGD("retrieved bundle id");
- __android_log_print(ANDROID_LOG_DEBUG, "CONTAINER", "getNumberOfConfiguredResources %s",str_bundleId);
- ResourceContainerImpl *container = ResourceContainerImpl::getImplInstance();
- vector< resourceInfo > resourceConfig;
- container->getResourceConfiguration(str_bundleId, &resourceConfig);
-
- return resourceConfig.size();
-}
-
-/*
- * Class: org_iotivity_resourcecontainer_bundle_api_BaseActivator
- * Method: getConfiguredResourceParams
- * Signature: (Ljava/lang/String;I)[Ljava/lang/String;
- */
-JNIEXPORT jobjectArray JNICALL
-Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeGetConfiguredResourceParams(
- JNIEnv *env, jobject obj, jstring bundleId, jint resourceId)
-{
- (void)obj;
- jobjectArray ret;
- ret = (jobjectArray) env->NewObjectArray(4, env->FindClass("java/lang/String"),
- env->NewStringUTF(""));
- if(bundleId != NULL){
- const char *str_bundleId = env->GetStringUTFChars(bundleId, 0);
-
- ResourceContainerImpl *container = ResourceContainerImpl::getImplInstance();
- vector< resourceInfo > resourceConfig;
- container->getResourceConfiguration(str_bundleId, &resourceConfig);
-
- if(resourceConfig.size() > resourceId && resourceId >=0){
- resourceInfo conf = resourceConfig[resourceId];
- env->SetObjectArrayElement(ret, 0, env->NewStringUTF(conf.name.c_str()));
- env->SetObjectArrayElement(ret, 1, env->NewStringUTF(conf.uri.c_str()));
- env->SetObjectArrayElement(ret, 2, env->NewStringUTF(conf.resourceType.c_str()));
- env->SetObjectArrayElement(ret, 3, env->NewStringUTF(conf.address.c_str()));
- }
- }
- return ret;
-}
-
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-/** @file jni_re_rcs_resource_container.h
- *
- * @brief This file contains the declaration of RCSResourceContainer
- * APIs for JNI implementation
- */
-
-#ifndef JNI_RCS_RESOURCE_CONTAINER_H_
-#define JNI_RCS_RESOURCE_CONTAINER_H_
-
-#include <jni.h>
-
-class JNIEnvWrapper;
-
-void initRCSResourceContainer(JNIEnvWrapper *);
-void clearRCSResourceContainer(JNIEnvWrapper *);
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeStartContainer
-(JNIEnv *, jobject, jstring);
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeStopContainer
-(JNIEnv *, jobject);
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeAddBundle
-(JNIEnv *, jobject, jstring bundleId, jstring bundleUri, jstring bundlePath, jstring activator,
- jobject params);
-
-JNIEXPORT jobject JNICALL
-Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeListBundles
-(JNIEnv *, jobject);
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeRemoveBundle
-(JNIEnv *, jobject, jstring bundleId);
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeStartBundle
-(JNIEnv *, jobject, jstring bundleId);
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeStopBundle
-(JNIEnv *, jobject, jstring bundleId);
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeAddResourceConfig
-(JNIEnv *, jobject, jstring bundleId, jstring resourceUri, jobject params);
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeRemoveResourceConfig
-(JNIEnv *, jobject, jstring bundleId, jstring resourceUri);
-
-JNIEXPORT jobject JNICALL
-Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeListBundleResources
-(JNIEnv *, jobject, jstring bundleId);
-
-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_nativeUnregisterBundleResource
- (JNIEnv *, jobject, jobject, jstring);
-
-JNIEXPORT jint JNICALL Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeGetNumberOfConfiguredResources
- (JNIEnv *, jobject, jstring);
-
-JNIEXPORT jobjectArray JNICALL Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeGetConfiguredResourceParams
- (JNIEnv *, jobject, jstring, jint);
-
-
-
-#ifdef __cplusplus
-}
-#endif
-#endif //JNI_RCS_RESOURCE_CONTAINER_H_
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-#include "JniRcsValue.h"
-
-#include "JNIEnvWrapper.h"
-#include "JniRcsResourceAttributes.h"
-#include "JavaClasses.h"
-#include "JavaExceptions.h"
-#include "JavaLocalRef.h"
-#include "Log.h"
-
-using namespace OIC::Service;
-
-#define LOG_TAG "JNI-RCSValue"
-
-#define CLS_NAME_VALUE_TYPE CLS_NAME_VALUE "$Type"
-#define CLS_NAME_VALUE_TYPEID CLS_NAME_VALUE "$TypeId"
-#define CLS_NAME_VALUE_NULL_TYPE CLS_NAME_VALUE "$NullType"
-
-namespace
-{
- jclass g_cls_RCSValue;
- jclass g_cls_Type;
- jclass g_cls_TypeId;
-
- jmethodID g_ctor_RCSValue;
-
- jmethodID g_smethod_Type_getDepth;
- jmethodID g_smethod_Type_getBaseTypeId;
-
- jmethodID g_method_RCSValue_getType;
-
- jfieldID g_field_RCSValue_mObject;
- jfieldID g_field_RCSValue_sNullValue;
-
- jobject g_obj_TypeId_Null;
- jobject g_obj_TypeId_Boolean;
- jobject g_obj_TypeId_Integer;
- jobject g_obj_TypeId_Double;
- jobject g_obj_TypeId_String;
- jobject g_obj_TypeId_Attributes;
- jobject g_obj_TypeId_Array;
-
- template< int >
- struct Int2Type{ };
-
- template< int DEPTH, typename BASE_TYPE >
- struct SeqType
- {
- typedef std::vector< typename SeqType< DEPTH - 1, BASE_TYPE >::type > type;
- };
-
- template< typename BASE_TYPE >
- struct SeqType< 0, BASE_TYPE >
- {
- typedef BASE_TYPE type;
- };
-
- template< typename T >
- struct BaseType
- {
- typedef T type;
- };
-
- template< typename T >
- struct BaseType< std::vector< T > >
- {
- typedef typename BaseType< T >::type type;
- };
-
-
- template< int D >
- struct ArrayPrefix
- {
- static constexpr char str[] = "";
- };
- template< int D >
- constexpr char ArrayPrefix< D >::str[];
-
- template<>
- struct ArrayPrefix< 1 >
- {
- static constexpr char str[] = "[";
- };
- constexpr char ArrayPrefix< 1 >::str[];
-
- template<>
- struct ArrayPrefix< 2 >
- {
- static constexpr char str[] = "[[";
- };
- constexpr char ArrayPrefix< 2 >::str[];
-
- struct PrimitiveType {
- static constexpr bool isPrimitive = true;
- };
-
- struct ObjectType {
- static constexpr bool isPrimitive = false;
- };
-
- template< typename T >
- struct JniTypeTrait;
-
- template<>
- struct JniTypeTrait< int >: public PrimitiveType
- {
- static_assert(sizeof(int) == sizeof(jint), "int and jint have different size!");
-
- static constexpr decltype(&JNIEnvWrapper::NewIntArray) newArrayFunc =
- &JNIEnvWrapper::NewIntArray;
- static constexpr decltype(&JNIEnvWrapper::SetIntArrayRegion) setArrayRegionFunc =
- &JNIEnvWrapper::SetIntArrayRegion;
-
- static constexpr decltype(&invoke_Integer_intValue<JNIEnvWrapper>) converter =
- &invoke_Integer_intValue<JNIEnvWrapper>;
-
- static constexpr decltype(&newIntegerObject<JNIEnvWrapper>) newObjectFunc =
- &newIntegerObject<JNIEnvWrapper>;
-
- static constexpr char className[] = "I";
- };
- constexpr char JniTypeTrait< int >::className[];
-
- template<>
- struct JniTypeTrait< bool >: public PrimitiveType
- {
- static_assert(sizeof(bool) == sizeof(jboolean), "bool and jboolean have different size!");
-
- static constexpr decltype(&JNIEnvWrapper::NewBooleanArray) newArrayFunc =
- &JNIEnvWrapper::NewBooleanArray;
- static constexpr decltype(&JNIEnvWrapper::SetBooleanArrayRegion) setArrayRegionFunc =
- &JNIEnvWrapper::SetBooleanArrayRegion;
-
- static constexpr decltype(&invoke_Boolean_booleanValue<JNIEnvWrapper>) converter =
- &invoke_Boolean_booleanValue<JNIEnvWrapper>;
-
- static constexpr decltype(&newBooleanObject<JNIEnvWrapper>) newObjectFunc =
- &newBooleanObject<JNIEnvWrapper>;
-
- static constexpr char className[] = "Z";
- };
- constexpr char JniTypeTrait< bool >::className[];
-
- template<>
- struct JniTypeTrait< double > : public PrimitiveType
- {
- static_assert(sizeof(double) == sizeof(jdouble), "double and jdouble have different size!");
-
- static constexpr decltype(&JNIEnvWrapper::NewDoubleArray) newArrayFunc =
- &JNIEnvWrapper::NewDoubleArray;
- static constexpr decltype(&JNIEnvWrapper::SetDoubleArrayRegion) setArrayRegionFunc =
- &JNIEnvWrapper::SetDoubleArrayRegion;
-
- static constexpr decltype(&invoke_Double_doubleValue<JNIEnvWrapper>) converter =
- &invoke_Double_doubleValue<JNIEnvWrapper>;
-
- static constexpr decltype(&newDoubleObject<JNIEnvWrapper>) newObjectFunc =
- &newDoubleObject<JNIEnvWrapper>;
-
- static constexpr char className[] = "D";
- };
- constexpr char JniTypeTrait< double >::className[];
-
- template<>
- struct JniTypeTrait< std::string >: public ObjectType
- {
- static constexpr decltype(&newStringObject<JNIEnvWrapper>) newObjectFunc =
- &newStringObject<JNIEnvWrapper>;
-
- static constexpr char className[] = "L" CLS_NAME_STRING ";";
- };
- constexpr char JniTypeTrait< std::string >::className[];
-
- template<>
- struct JniTypeTrait< RCSResourceAttributes >: public ObjectType
- {
- inline static jobject newObjectFunc(JNIEnvWrapper* env, const RCSResourceAttributes& value)
- {
- return newAttributesObject(env, value);
- }
-
- inline static RCSResourceAttributes converter(JNIEnvWrapper* env, jobject obj)
- {
- return toNativeAttributes(env, obj);
- }
-
- static constexpr char className[] = "L" CLS_NAME_RESOURCEATTRIBUTES ";";
- };
- constexpr char JniTypeTrait< RCSResourceAttributes >::className[];
-
- inline void toNativeValue(JNIEnvWrapper* env, jobject obj, std::string& result, Int2Type< 0 >)
- {
- result = toStdString(env, static_cast< jstring >(obj));
- }
-
- template< typename T >
- inline void toNativeValue(JNIEnvWrapper* env, jobject obj, T& result, Int2Type< 0 >)
- {
- result = JniTypeTrait< T >::converter(env, obj);
- }
-
- template< int DEPTH, typename RET >
- inline void toNativeValue(JNIEnvWrapper* env, jobject obj, RET& result, Int2Type< DEPTH >)
- {
- const auto arrayObj = static_cast< jobjectArray >(obj);
- result.resize(env->GetArrayLength(arrayObj));
-
- for (typename RET::size_type i = 0; i < result.size(); ++i)
- {
- JavaLocalObject elementObj{ env, env->GetObjectArrayElement(arrayObj, i) };
-
- toNativeValue(env, elementObj, result[i], Int2Type< DEPTH - 1 >{ });
- }
- }
-
- template< typename T >
- inline typename std::enable_if< JniTypeTrait< T >::isPrimitive >::type
- toNativeValue(JNIEnvWrapper* env, jobject obj, std::vector< T >& result, Int2Type< 1 >)
- {
- const auto arrayObj = static_cast< jobjectArray >(obj);
- const jsize arraySize = env->GetArrayLength(arrayObj);
-
- T* raw = static_cast< T* >(env->GetPrimitiveArrayCritical(arrayObj, nullptr));
-
- try
- {
- result = std::vector< T >(raw, raw + arraySize);
- } catch (...)
- {
- }
-
- env->ReleasePrimitiveArrayCritical(arrayObj, raw, JNI_ABORT);
- }
-
- template< typename T >
- inline typename std::enable_if< !JniTypeTrait< T >::isPrimitive >::type
- toNativeValue(JNIEnvWrapper* env, jobject obj, std::vector< T >& result, Int2Type< 1 >)
- {
- const auto arrayObj = static_cast< jobjectArray >(obj);
- const jsize arraySize = env->GetArrayLength(arrayObj);
-
- result.resize(arraySize);
-
- for (typename std::vector< T >::size_type i = 0; i < result.size(); ++i)
- {
- JavaLocalObject elementObj{ env, env->GetObjectArrayElement(arrayObj, i) };
- toNativeValue(env, elementObj, result[i], Int2Type< 0 >{ });
- }
- }
-
-
- template< typename T, int DEPTH, typename RET = typename SeqType< DEPTH, T >::type >
- inline RET toNativeValue(JNIEnvWrapper* env, jobject obj)
- {
- static_assert(DEPTH >= 0, "DEPTH must be positive!");
-
- typename SeqType< DEPTH, T >::type result;
-
- toNativeValue(env, obj, result, Int2Type< DEPTH >{ });
-
- return result;
- }
-
- template< typename T >
- inline RCSResourceAttributes::Value toNativeValue(JNIEnvWrapper* env, jobject val, int depth)
- {
- switch (depth)
- {
- case 0: return toNativeValue< T, 0 >(env, val);
- case 1: return toNativeValue< T, 1 >(env, val);
- case 2: return toNativeValue< T, 2 >(env, val);
- case 3: return toNativeValue< T, 3 >(env, val);
- }
-
- return {};
- }
-
- inline RCSResourceAttributes::Value toNativeValue(JNIEnvWrapper* env, jobject val, int depth,
- RCSResourceAttributes::TypeId typeId)
- {
- LOGD("toNativeValue depth is %d", depth);
- EXPECT_RET(depth >= 0 && depth <= 3, "Unsupported depth!", {});
-
- switch (typeId)
- {
- case RCSResourceAttributes::TypeId::NULL_T: return { };
-
- case RCSResourceAttributes::TypeId::BOOL:
- return toNativeValue< bool >(env, val, depth);
-
- case RCSResourceAttributes::TypeId::INT:
- return toNativeValue< int >(env, val, depth);
-
- case RCSResourceAttributes::TypeId::DOUBLE:
- return toNativeValue< double >(env, val, depth);
-
- case RCSResourceAttributes::TypeId::STRING:
- return toNativeValue< std::string >(env, val, depth);
-
- case RCSResourceAttributes::TypeId::ATTRIBUTES:
- return toNativeValue< RCSResourceAttributes >(env, val, depth);
- }
-
- throwRCSException(env, "Failed to convert RCSValue : unknown type id");
- return {};
- }
-
- template< typename T, int DEPTH, typename BASE_TYPE = typename BaseType< T >::type >
- inline jobject createJavaObject(JNIEnvWrapper* env, const T& value, Int2Type< DEPTH >)
- {
- const std::string elementClsName{ std::string{ ArrayPrefix< DEPTH - 1 >::str }
- + JniTypeTrait< BASE_TYPE >::className };
-
- LOGD("create array %dd, %s", DEPTH, elementClsName.c_str());
-
- auto cls = env->FindClass(elementClsName.c_str());
-
- const jsize len = value.size();
-
- auto array = env->NewObjectArray(len, cls, nullptr);
-
- for(jsize i = 0; i < len; ++i)
- {
- auto element = createJavaObject(env, value[i], Int2Type< DEPTH - 1>{ });
- env->SetObjectArrayElement(array, i, element);
- }
-
- return array;
- }
-
- template< typename T, typename TRAIT = JniTypeTrait< T > >
- inline typename std::enable_if< TRAIT::isPrimitive, jobject >::type
- createJavaObject(JNIEnvWrapper* env, const std::vector< T >& value, Int2Type< 1 >)
- {
- LOGD("create array with newArray");
- const jsize len = value.size();
-
- auto array = (env->*TRAIT::newArrayFunc)(len);
-
- if (!value.empty()) (env->*TRAIT::setArrayRegionFunc)(array, 0, len, &value[0]);
-
- return array;
- }
-
- inline jobject createJavaObject(JNIEnvWrapper* env, const std::vector< bool >& value, Int2Type< 1 >)
- {
- const auto len = value.size();
- LOGD("create bool array with newArray %d", len);
-
- auto arrayObj = env->NewBooleanArray(len);
-
- bool* raw = static_cast< bool* >(env->GetPrimitiveArrayCritical(arrayObj, 0));
-
- std::copy(value.begin(), value.end(), raw);
-
- env->ReleasePrimitiveArrayCritical(arrayObj, raw, 0);
-
- return arrayObj;
- }
-
- template< typename T, typename TRAIT = JniTypeTrait< T > >
- inline jobject createJavaObject(JNIEnvWrapper* env, const T& value, Int2Type< 0 >)
- {
- LOGD("createJavaObject 0-depth");
- return TRAIT::newObjectFunc(env, value);
- }
-
- template< int DEPTH >
- inline jobject createJavaObject(JNIEnvWrapper* env, const RCSResourceAttributes::Value& value)
- {
- const auto type = value.getType();
- const auto baseType = RCSResourceAttributes::Type::getBaseTypeId(type);
-
- LOGD("createJavaObject with DEPTH. type is %d", static_cast< int >(baseType));
-
- switch (baseType)
- {
- case RCSResourceAttributes::TypeId::NULL_T:
- return env->GetStaticObjectField(g_cls_RCSValue, g_field_RCSValue_sNullValue);
-
- case RCSResourceAttributes::TypeId::BOOL:
- return createJavaObject(env, value.get< typename SeqType< DEPTH, bool >::type >(),
- Int2Type< DEPTH >{ });
-
- case RCSResourceAttributes::TypeId::INT:
- return createJavaObject(env, value.get< typename SeqType< DEPTH, int >::type >(),
- Int2Type< DEPTH >{ });
-
- case RCSResourceAttributes::TypeId::DOUBLE:
- return createJavaObject(env, value.get< typename SeqType< DEPTH, double >::type >(),
- Int2Type< DEPTH >{ });
-
- case RCSResourceAttributes::TypeId::STRING:
- return createJavaObject(env,
- value.get< typename SeqType< DEPTH, std::string >::type >(),
- Int2Type< DEPTH >{ });
-
- case RCSResourceAttributes::TypeId::ATTRIBUTES:
- return createJavaObject(env,
- value.get< typename SeqType< DEPTH, RCSResourceAttributes >::type >(),
- Int2Type< DEPTH >{ });
- }
-
- LOGE("Unknown type!");
-
- return nullptr;
- }
-
- inline jobject createJavaObject(JNIEnvWrapper* env, const RCSResourceAttributes::Value& value)
- {
- const auto type = value.getType();
- const auto depth = RCSResourceAttributes::Type::getDepth(type);
-
- EXPECT_RET(depth >= 0 && depth <= 3, "Unsupported depth!", {});
-
- switch (depth)
- {
- case 0: return createJavaObject< 0 >(env, value);
- case 1: return createJavaObject< 1 >(env, value);
- case 2: return createJavaObject< 2 >(env, value);
- case 3: return createJavaObject< 3 >(env, value);
- }
-
- return nullptr;
- }
-
- inline RCSResourceAttributes::TypeId toNativeTypeId(JNIEnvWrapper* env, jobject typeIdObj)
- {
- typedef RCSResourceAttributes::TypeId TypeId;
-
- if (env->IsSameObject(g_obj_TypeId_Null, typeIdObj)) return TypeId::NULL_T;
- if (env->IsSameObject(g_obj_TypeId_Boolean, typeIdObj)) return TypeId::BOOL;
- if (env->IsSameObject(g_obj_TypeId_Integer, typeIdObj)) return TypeId::INT;
- if (env->IsSameObject(g_obj_TypeId_Double, typeIdObj)) return TypeId::DOUBLE;
- if (env->IsSameObject(g_obj_TypeId_String, typeIdObj)) return TypeId::STRING;
- if (env->IsSameObject(g_obj_TypeId_Attributes, typeIdObj)) return TypeId::ATTRIBUTES;
- if (env->IsSameObject(g_obj_TypeId_Array, typeIdObj)) return TypeId::VECTOR;
-
- throwRCSException(env, "Failed to convert RCSValue : unknown type id");
- return TypeId::NULL_T;
- }
-
- jobject getTypeIdObj(JNIEnvWrapper* env, const char* name)
- {
- return env->NewGlobalRef(
- env->GetStaticObjectField(g_cls_TypeId, name, AS_SIG(CLS_NAME_VALUE_TYPEID)));
- }
-}
-
-void initRCSValue(JNIEnvWrapper* env)
-{
- g_cls_RCSValue = env->FindClassAsGlobalRef(CLS_NAME_VALUE);
- g_ctor_RCSValue = env->GetConstructorID(g_cls_RCSValue, "(" AS_SIG(CLS_NAME_OBJECT) ")V");
-
- g_method_RCSValue_getType = env->GetMethodID(g_cls_RCSValue, "getType",
- "()" AS_SIG(CLS_NAME_VALUE_TYPE));
-
- g_field_RCSValue_mObject = env->GetFieldID(g_cls_RCSValue, "mObject", AS_SIG(CLS_NAME_OBJECT));
-
- g_field_RCSValue_sNullValue = env->GetStaticFieldID(g_cls_RCSValue, "sNullValue",
- AS_SIG(CLS_NAME_VALUE_NULL_TYPE));
-
- g_cls_Type = env->FindClassAsGlobalRef(CLS_NAME_VALUE_TYPE);
-
- g_smethod_Type_getBaseTypeId = env->GetStaticMethodID(g_cls_Type, "getBaseTypeId",
- "(" AS_SIG(CLS_NAME_VALUE_TYPE) ")" AS_SIG(CLS_NAME_VALUE_TYPEID));
-
- g_smethod_Type_getDepth = env->GetStaticMethodID(g_cls_Type, "getDepth",
- "(" AS_SIG(CLS_NAME_VALUE_TYPE) ")I");
-
- g_cls_TypeId = env->FindClassAsGlobalRef(CLS_NAME_VALUE_TYPEID);
-
- g_obj_TypeId_Null = getTypeIdObj(env, "NULL");
- g_obj_TypeId_Boolean = getTypeIdObj(env, "BOOLEAN");
- g_obj_TypeId_Integer = getTypeIdObj(env, "INTEGER");
- g_obj_TypeId_Double = getTypeIdObj(env, "DOUBLE");
- g_obj_TypeId_String = getTypeIdObj(env, "STRING");
- g_obj_TypeId_Attributes = getTypeIdObj(env, "ATTRIBUTES");
- g_obj_TypeId_Array = getTypeIdObj(env, "ARRAY");
-}
-
-void clearRCSValue(JNIEnvWrapper* env)
-{
- env->DeleteGlobalRef(g_cls_RCSValue);
- env->DeleteGlobalRef(g_cls_Type);
- env->DeleteGlobalRef(g_cls_TypeId);
-
- env->DeleteGlobalRef(g_obj_TypeId_Null);
- env->DeleteGlobalRef(g_obj_TypeId_Boolean);
- env->DeleteGlobalRef(g_obj_TypeId_Integer);
- env->DeleteGlobalRef(g_obj_TypeId_Double);
- env->DeleteGlobalRef(g_obj_TypeId_String);
- env->DeleteGlobalRef(g_obj_TypeId_Attributes);
- env->DeleteGlobalRef(g_obj_TypeId_Array);
-}
-
-RCSResourceAttributes::Value toNativeAttrsValue(JNIEnv* env, jobject valueObj)
-{
- JNIEnvWrapper envWrapper(env);
-
- try
- {
- return toNativeAttrsValue(&envWrapper, valueObj);
- }
- catch (const JavaException&)
- {
- return { };
- }
-}
-
-RCSResourceAttributes::Value toNativeAttrsValue(JNIEnvWrapper* env, jobject valueObj)
-{
- LOGD("Type object");
- auto typeObj = env->CallObjectMethod(valueObj, g_method_RCSValue_getType);
- LOGD("Type base type object");
- auto typeIdObj = env->CallStaticObjectMethod(g_cls_Type, g_smethod_Type_getBaseTypeId, typeObj);
- LOGD("Type getDepth");
- auto depth = env->CallStaticIntMethod(g_cls_Type, g_smethod_Type_getDepth, typeObj);
- LOGD("Type get object field");
- auto memObj = env->GetObjectField(valueObj, g_field_RCSValue_mObject);
-
- LOGD("Type to native value");
- auto ret = toNativeValue(env, memObj, depth, toNativeTypeId(env, typeIdObj));
-
- if (env->get()->ExceptionCheck()) throw JavaException();
-
- return ret;
-}
-
-jobject newRCSValueObject(JNIEnv* env, const RCSResourceAttributes::Value& value)
-{
- JNIEnvWrapper envWrapper(env);
-
- try
- {
- return newRCSValueObject(&envWrapper, value);
- }
- catch (const JavaException&)
- {
- return {};
- }
-}
-
-jobject newRCSValueObject(JNIEnvWrapper* env, const RCSResourceAttributes::Value& value)
-{
- LOGD("newRCSValueObject");
-
- JavaLocalObject valueObj{ env, createJavaObject(env, value) };
-
- if (env->get()->ExceptionCheck()) throw JavaException();
-
- return env->NewObject(g_cls_RCSValue, g_ctor_RCSValue, valueObj.get());
-}
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-#ifndef JNI_RCS_VALUE_H_
-#define JNI_RCS_VALUE_H_
-
-#include <jni.h>
-
-#include "RCSResourceAttributes.h"
-
-class JNIEnvWrapper;
-
-void initRCSValue(JNIEnvWrapper*);
-void clearRCSValue(JNIEnvWrapper*);
-
-OIC::Service::RCSResourceAttributes::Value toNativeAttrsValue(JNIEnv*, jobject);
-OIC::Service::RCSResourceAttributes::Value toNativeAttrsValue(JNIEnvWrapper*, jobject);
-
-jobject newRCSValueObject(JNIEnv*, const OIC::Service::RCSResourceAttributes::Value&);
-jobject newRCSValueObject(JNIEnvWrapper*, const OIC::Service::RCSResourceAttributes::Value&);
-
-#endif // JNI_RCS_VALUE_H_
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-#ifndef RCS_JNI_ENV_WRAPPER_H_
-#define RCS_JNI_ENV_WRAPPER_H_
-
-#include <jni.h>
-
-#include <exception>
-
-#include "JavaLocalRef.h"
-
-class JavaException: public std::exception
-{
-};
-
-class JNIEnvWrapper
-{
- public:
- JNIEnvWrapper() noexcept : m_env { } {}
- JNIEnvWrapper(JNIEnv *env) noexcept : m_env { env } {}
-
- JNIEnvWrapper &operator=(JNIEnv *env) noexcept
- {
- m_env = env;
- return *this;
- }
-
- jboolean IsSameObject(jobject lhs, jobject rhs)
- {
- return m_env->IsSameObject(lhs, rhs);
- }
-
- jclass GetObjectClass(jobject obj)
- {
- auto ret = m_env->GetObjectClass(obj);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- jclass FindClass(const char *name)
- {
- auto ret = m_env->FindClass(name);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- jclass FindClassAsGlobalRef(const char *name)
- {
- JavaLocalClass cls { m_env, FindClass(name) };
-
- return NewGlobalRef(cls);
- }
-
- jobject NewGlobalRef(jobject obj)
- {
- auto ret = m_env->NewGlobalRef(obj);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- template<typename T>
- T NewGlobalRef(T obj)
- {
- auto ret = static_cast< T >(m_env->NewGlobalRef(obj));
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- template<typename T>
- T NewGlobalRef(const JavaLocalRef< T > &obj)
- {
- auto ret = static_cast< T >(m_env->NewGlobalRef(obj));
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- void DeleteGlobalRef(jobject obj)
- {
- m_env->DeleteGlobalRef(obj);
- }
-
- jobject NewObject(jclass cls, jmethodID ctor, ...)
- {
- va_list args;
- va_start(args, ctor);
- auto ret = m_env->NewObjectV(cls, ctor, args);
- va_end(args);
-
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- jstring NewStringUTF(const char *str)
- {
- auto ret = m_env->NewStringUTF(str);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- const char *GetStringUTFChars(jstring str, jboolean *isCopy)
- {
- auto ret = m_env->GetStringUTFChars(str, isCopy);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- void ReleaseStringUTFChars(jstring str, const char *chars)
- {
- m_env->ReleaseStringUTFChars(str, chars);
- if (m_env->ExceptionCheck()) throw JavaException();
- }
-
- jmethodID GetConstructorID(jclass cls, const char *sig)
- {
- auto ret = m_env->GetMethodID(cls, "<init>", sig);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- jmethodID GetMethodID(jclass cls, const char *name, const char *sig)
- {
- auto ret = m_env->GetMethodID(cls, name, sig);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- jmethodID GetStaticMethodID(jclass cls, const char *name, const char *sig)
- {
- auto ret = m_env->GetStaticMethodID(cls, name, sig);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
-
- jfieldID GetFieldID(jclass cls, const char *name, const char *sig)
- {
- auto ret = m_env->GetFieldID(cls, name, sig);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- jfieldID GetStaticFieldID(jclass cls, const char *name, const char *sig)
- {
- auto ret = m_env->GetStaticFieldID(cls, name, sig);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- jobject GetStaticObjectField(jclass cls, jfieldID fieldId)
- {
- auto ret = m_env->GetStaticObjectField(cls, fieldId);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- jobject GetStaticObjectField(jclass cls, const char *name, const char *sig)
- {
- return GetStaticObjectField(cls, GetStaticFieldID(cls, name, sig));
- }
-
- jint GetIntField(jobject obj, jfieldID fieldId)
- {
- auto ret = m_env->GetIntField(obj, fieldId);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- jlong GetLongField(jobject obj, jfieldID fieldId)
- {
- auto ret = m_env->GetLongField(obj, fieldId);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- void SetLongField(jobject obj, jfieldID fieldId, jlong val)
- {
- m_env->SetLongField(obj, fieldId, val);
- if (m_env->ExceptionCheck()) throw JavaException();
- }
-
- jobject GetObjectField(jobject obj, jfieldID fieldId)
- {
- auto ret = m_env->GetObjectField(obj, fieldId);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- jint CallStaticIntMethod(jclass cls, jmethodID methodId, ...)
- {
- va_list args;
- va_start(args, methodId);
- auto ret = m_env->CallStaticIntMethodV(cls, methodId, args);
- va_end(args);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- jobject CallStaticObjectMethod(jclass cls, jmethodID methodId, ...)
- {
- va_list args;
- va_start(args, methodId);
- auto ret = m_env->CallStaticObjectMethodV(cls, methodId, args);
- va_end(args);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- void CallVoidMethod(jobject obj, jmethodID methodId, ...)
- {
- va_list args;
- va_start(args, methodId);
- m_env->CallVoidMethodV(obj, methodId, args);
- va_end(args);
- if (m_env->ExceptionCheck()) throw JavaException();
- }
-
- jboolean CallBooleanMethod(jobject obj, jmethodID methodId, ...)
- {
- va_list args;
- va_start(args, methodId);
- auto ret = m_env->CallBooleanMethodV(obj, methodId, args);
- va_end(args);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- jint CallIntMethod(jobject obj, jmethodID methodId, ...)
- {
- va_list args;
- va_start(args, methodId);
- auto ret = m_env->CallIntMethod(obj, methodId, args);
- va_end(args);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- jdouble CallDoubleMethod(jobject obj, jmethodID methodId, ...)
- {
- va_list args;
- va_start(args , methodId);
- auto ret = m_env->CallDoubleMethod(obj, methodId, args);
- va_end(args);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
-
- jobject CallObjectMethod(jobject obj, jmethodID methodId, ...)
- {
- va_list args;
- va_start(args, methodId);
- auto ret = m_env->CallObjectMethodV(obj, methodId, args);
- va_end(args);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- jbooleanArray NewBooleanArray(jsize len)
- {
- auto ret = m_env->NewBooleanArray(len);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- jintArray NewIntArray(jsize len)
- {
- auto ret = m_env->NewIntArray(len);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- jdoubleArray NewDoubleArray(jsize len)
- {
- auto ret = m_env->NewDoubleArray(len);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- jobjectArray NewObjectArray(jsize len, jclass cls, jobject init)
- {
- auto ret = m_env->NewObjectArray(len, cls, init);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- jsize GetArrayLength(jarray array)
- {
- auto ret = m_env->GetArrayLength(array);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- jobject GetObjectArrayElement(jobjectArray array, jsize index)
- {
- auto ret = m_env->GetObjectArrayElement(array, index);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- void SetObjectArrayElement(jobjectArray array, jsize index, jobject val)
- {
- m_env->SetObjectArrayElement(array, index, val);
- if (m_env->ExceptionCheck()) throw JavaException();
- }
-
- void SetBooleanArrayRegion(jbooleanArray array, jsize start, jsize len, const jboolean *buf)
- {
- m_env->SetBooleanArrayRegion(array, start, len, buf);
- if (m_env->ExceptionCheck()) throw JavaException();
- }
-
- void SetIntArrayRegion(jintArray array, jsize start, jsize len, const jint *buf)
- {
- m_env->SetIntArrayRegion(array, start, len, buf);
- if (m_env->ExceptionCheck()) throw JavaException();
- }
-
- void SetDoubleArrayRegion(jdoubleArray array, jsize start, jsize len, const jdouble *buf)
- {
- m_env->SetDoubleArrayRegion(array, start, len, buf);
- if (m_env->ExceptionCheck()) throw JavaException();
- }
-
- void *GetPrimitiveArrayCritical(jarray array, jboolean *isCopy)
- {
- auto ret = m_env->GetPrimitiveArrayCritical(array, isCopy);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- void ReleasePrimitiveArrayCritical(jarray array, void *carray, int mode)
- {
- m_env->ReleasePrimitiveArrayCritical(array, carray, mode);
- if (m_env->ExceptionCheck()) throw JavaException();
- }
-
- void ThrowNew(jclass cls, const char *msg)
- {
- m_env->ThrowNew(cls, msg);
- throw JavaException();
- }
-
- void ExceptionDescribe() const noexcept
- {
- m_env->ExceptionDescribe();
- }
-
- void ExceptionClear() noexcept
- {
- m_env->ExceptionClear();
- }
-
- jboolean ExceptionCheck() const noexcept
- {
- return m_env->ExceptionCheck();
- }
-
- operator bool() const noexcept
- {
- return m_env != nullptr;
- }
-
- JNIEnv *get() const
- {
- return m_env;
- }
-
- private:
- JNIEnv *m_env;
-};
-
-
-
-#endif // RCS_JNI_ENV_WRAPPER_H_
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-#include "JavaClasses.h"
-
-#include "JNIEnvWrapper.h"
-
-jclass g_cls_String;
-jclass g_cls_Integer;
-jclass g_cls_Double;
-jclass g_cls_Boolean;
-
-jclass g_cls_ArrayList;
-jclass g_cls_Set;
-jclass g_cls_Map;
-jclass g_cls_MapEntry;
-jclass g_cls_Iterator;
-
-jmethodID g_method_Boolean_booleanValue;
-jmethodID g_method_Integer_intValue;
-jmethodID g_method_Double_doubleValue;
-
-jmethodID g_method_Collection_add;
-
-jmethodID g_method_Set_iterator;
-
-jmethodID g_method_Map_entrySet;
-jmethodID g_method_Map_put;
-
-jmethodID g_method_MapEntry_getKey;
-jmethodID g_method_MapEntry_getValue;
-
-jmethodID g_method_Iterator_hasNext;
-jmethodID g_method_Iterator_next;
-
-jmethodID g_ctor_Boolean;
-jmethodID g_ctor_Integer;
-jmethodID g_ctor_Double;
-
-jmethodID g_ctor_ArrayList;
-
-namespace
-{
- inline void initPrimitiveTypes(JNIEnvWrapper* env)
- {
- g_cls_Boolean = env->FindClassAsGlobalRef(CLS_NAME_BOOLEAN);
- g_ctor_Boolean = env->GetConstructorID(g_cls_Boolean, "(Z)V");
- g_method_Boolean_booleanValue = env->GetMethodID(g_cls_Boolean, "booleanValue", "()Z");
-
- g_cls_Integer = env->FindClassAsGlobalRef(CLS_NAME_INTEGER);
- g_ctor_Integer = env->GetConstructorID(g_cls_Integer, "(I)V");
- g_method_Integer_intValue = env->GetMethodID(g_cls_Integer, "intValue", "()I");
-
- g_cls_Double = env->FindClassAsGlobalRef(CLS_NAME_DOUBLE);
- g_ctor_Double = env->GetConstructorID(g_cls_Double, "(D)V");
- g_method_Double_doubleValue = env->GetMethodID(g_cls_Double, "doubleValue", "()D");
-
- g_cls_String = env->FindClassAsGlobalRef(CLS_NAME_STRING);
- }
-}
-
-void initJavaClasses(JNIEnvWrapper* env)
-{
- initPrimitiveTypes(env);
-
- auto clsCollection = env->FindClass(CLS_NAME_COLLECTION);
- g_method_Collection_add = env->GetMethodID(clsCollection, "add",
- "(" AS_SIG(CLS_NAME_OBJECT) ")Z");
-
- g_cls_ArrayList = env->FindClassAsGlobalRef(CLS_NAME_ARRAY_LIST);
- g_ctor_ArrayList = env->GetConstructorID(g_cls_ArrayList, "()V");
-
- g_cls_Set = env->FindClassAsGlobalRef(CLS_NAME_SET);
- g_method_Set_iterator = env->GetMethodID(g_cls_Set, "iterator", "()" AS_SIG(CLS_NAME_ITERATOR));
-
- g_cls_Map = env->FindClassAsGlobalRef(CLS_NAME_MAP);
- g_method_Map_entrySet = env->GetMethodID(g_cls_Map, "entrySet", "()" AS_SIG(CLS_NAME_SET));
- g_method_Map_put = env->GetMethodID(g_cls_Map, "put",
- "(" AS_SIG(CLS_NAME_OBJECT) AS_SIG(CLS_NAME_OBJECT) ")" AS_SIG(CLS_NAME_OBJECT));
-
- g_cls_MapEntry = env->FindClassAsGlobalRef(CLS_NAME_MAP_ENTRY);
- g_method_MapEntry_getKey = env->GetMethodID(g_cls_MapEntry, "getKey",
- "()" AS_SIG(CLS_NAME_OBJECT));
- g_method_MapEntry_getValue = env->GetMethodID(g_cls_MapEntry, "getValue",
- "()" AS_SIG(CLS_NAME_OBJECT));
-
- g_cls_Iterator = env->FindClassAsGlobalRef(CLS_NAME_ITERATOR);
- g_method_Iterator_hasNext = env->GetMethodID(g_cls_Iterator, "hasNext", "()Z");
- g_method_Iterator_next = env->GetMethodID(g_cls_Iterator, "next", "()" AS_SIG(CLS_NAME_OBJECT));
-}
-
-void clearJavaClasses(JNIEnvWrapper* env)
-{
- env->DeleteGlobalRef(g_cls_Boolean);
- env->DeleteGlobalRef(g_cls_Integer);
- env->DeleteGlobalRef(g_cls_Double);
- env->DeleteGlobalRef(g_cls_String);
- env->DeleteGlobalRef(g_cls_Set);
- env->DeleteGlobalRef(g_cls_Map);
- env->DeleteGlobalRef(g_cls_MapEntry);
- env->DeleteGlobalRef(g_cls_Iterator);
-}
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-#ifndef JAVA_CLASSES_H_
-#define JAVA_CLASSES_H_
-
-#include <jni.h>
-
-#include <string>
-
-#define PACKAGE_NAME "org/iotivity/service/resourcecontainer"
-
-#define CLS_NAME_VALUE PACKAGE_NAME "/RcsValue"
-
-#define CLS_NAME_RESOURCEATTRIBUTES PACKAGE_NAME "/RcsResourceAttributes"
-
-#define CLS_NAME_OBJECT "java/lang/Object"
-#define CLS_NAME_STRING "java/lang/String"
-#define CLS_NAME_INTEGER "java/lang/Integer"
-#define CLS_NAME_DOUBLE "java/lang/Double"
-#define CLS_NAME_BOOLEAN "java/lang/Boolean"
-
-#define CLS_NAME_COLLECTION "java/util/Collection"
-#define CLS_NAME_ARRAY_LIST "java/util/ArrayList"
-#define CLS_NAME_SET "java/util/Set"
-#define CLS_NAME_MAP "java/util/Map"
-#define CLS_NAME_MAP_ENTRY "java/util/Map$Entry"
-#define CLS_NAME_ITERATOR "java/util/Iterator"
-
-#define AS_SIG(CLS_NAME) "L" CLS_NAME ";"
-
-class JNIEnvWrapper;
-
-extern jclass g_cls_Integer;
-extern jclass g_cls_Double;
-extern jclass g_cls_Boolean;
-extern jclass g_cls_String;
-
-extern jclass g_cls_ArrayList;
-extern jclass g_cls_Set;
-extern jclass g_cls_Map;
-extern jclass g_cls_MapEntry;
-extern jclass g_cls_Iterator;
-
-extern jmethodID g_method_Boolean_booleanValue;
-extern jmethodID g_method_Integer_intValue;
-extern jmethodID g_method_Double_doubleValue;
-
-extern jmethodID g_method_Collection_add;
-
-extern jmethodID g_method_Set_iterator;
-
-extern jmethodID g_method_Map_entrySet;
-extern jmethodID g_method_Map_put;
-
-extern jmethodID g_method_MapEntry_getKey;
-extern jmethodID g_method_MapEntry_getValue;
-
-extern jmethodID g_method_Iterator_hasNext;
-extern jmethodID g_method_Iterator_next;
-
-extern jmethodID g_ctor_Boolean;
-extern jmethodID g_ctor_Integer;
-extern jmethodID g_ctor_Double;
-
-extern jmethodID g_ctor_ArrayList;
-void initJavaClasses(JNIEnvWrapper *);
-void clearJavaClasses(JNIEnvWrapper *);
-
-template< typename ENV >
-inline jobject newBooleanObject(ENV* env, bool value)
-{
- return env->NewObject(g_cls_Boolean, g_ctor_Boolean, value);
-}
-
-template< typename ENV >
-inline jobject newIntegerObject(ENV* env, int value)
-{
- return env->NewObject(g_cls_Integer, g_ctor_Integer, value);
-}
-
-template< typename ENV >
-inline jobject newDoubleObject(ENV* env, double value)
-{
- return env->NewObject(g_cls_Double, g_ctor_Double, value);
-}
-
-template< typename ENV >
-inline jstring newStringObject(ENV* env, const std::string& value)
-{
- return env->NewStringUTF(value.c_str());
-}
-
-template< typename ENV >
-inline jstring newStringObjectCstr(ENV* env, const char* value)
-{
- return env->NewStringUTF(value);
-}
-
-template< typename ENV >
-inline std::string toStdString(ENV* env, jstring obj)
-{
- if (!obj) return "";
-
- auto cstr = env->GetStringUTFChars(obj, nullptr);
-
- if (!cstr) return "";
-
- std::string result{ cstr };
-
- env->ReleaseStringUTFChars(obj, cstr);
-
- return result;
-}
-
-template< typename ENV >
-inline jobject newArrayList(ENV* env)
-{
- return env->NewObject(g_cls_ArrayList, g_ctor_ArrayList);
-}
-
-template< typename ENV >
-inline bool invoke_Boolean_booleanValue(ENV* env, jobject obj)
-{
- return env->CallBooleanMethod(obj, g_method_Boolean_booleanValue);
-}
-
-template< typename ENV >
-inline int invoke_Integer_intValue(ENV* env, jobject obj)
-{
- return env->CallIntMethod(obj, g_method_Integer_intValue);
-}
-
-template< typename ENV >
-inline double invoke_Double_doubleValue(ENV* env, jobject obj)
-{
- return env->CallDoubleMethod(obj, g_method_Double_doubleValue);
-}
-
-template< typename ENV >
-inline jboolean invoke_Collection_add(ENV* env, jobject collectionObj, jobject valueObj)
-{
- return env->CallBooleanMethod(collectionObj, g_method_Collection_add, valueObj);
-}
-
-template< typename ENV >
-inline jobject invoke_Map_entrySet(ENV* env, jobject mapObj)
-{
- return env->CallObjectMethod(mapObj, g_method_Map_entrySet);
-}
-
-template< typename ENV >
-inline jobject invoke_Map_put(ENV* env, jobject mapObj, jobject keyObj, jobject valueObj)
-{
- return env->CallObjectMethod(mapObj, g_method_Map_put, keyObj, valueObj);
-}
-
-template< typename ENV >
-inline jobject invoke_MapEntry_getKey(ENV* env, jobject entryObj)
-{
- return env->CallObjectMethod(entryObj, g_method_MapEntry_getKey);
-}
-
-template< typename ENV >
-inline jobject invoke_MapEntry_getValue(ENV* env, jobject entryObj)
-{
- return env->CallObjectMethod(entryObj, g_method_MapEntry_getValue);
-}
-
-template< typename ENV >
-inline jobject invoke_Set_iterator(ENV* env, jobject setObj)
-{
- return env->CallObjectMethod(setObj, g_method_Set_iterator);
-}
-
-template< typename ENV >
-inline bool invoke_Iterator_hasNext(ENV* env, jobject iterObj)
-{
- return env->CallBooleanMethod(iterObj, g_method_Iterator_hasNext);
-}
-
-template< typename ENV >
-inline jobject invoke_Iterator_next(ENV* env, jobject iterObj)
-{
- return env->CallObjectMethod(iterObj, g_method_Iterator_next);
-}
-
-#endif // JAVA_CLASSES_H_
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-#include "JavaExceptions.h"
-
-#include "JNIEnvWrapper.h"
-#include "Verify.h"
-
-#include "RCSException.h"
-
-namespace
-{
- jclass g_cls_PlatformException;
-
- jmethodID g_ctor_PlatformException;
-}
-
-void initJavaExceptions(JNIEnvWrapper* env)
-{
- /*g_cls_PlatformException = env->FindClassAsGlobalRef(EXC_NAME_PLATFORM);
- g_ctor_PlatformException = env->GetConstructorID(g_cls_PlatformException,
- "(" AS_SIG(CLS_NAME_STRING) "I)V");*/
-}
-
-void clearJavaExceptions(JNIEnvWrapper* env)
-{
- //env->DeleteGlobalRef(g_cls_PlatformException);
-}
-
-void throwPlatformException(JNIEnv* env, const OIC::Service::RCSPlatformException& e)
-{
- /*auto msg = newStringObject(env, e.getReason());
- VERIFY_NO_EXC(env);
-
- auto exObj = env->NewObject(g_cls_PlatformException, g_ctor_PlatformException,
- msg, e.getReasonCode());
- VERIFY_NO_EXC(env);
-
- env->Throw(static_cast< jthrowable >(exObj));*/
-}
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-#ifndef JAVA_EXCEPTIONS_H_
-#define JAVA_EXCEPTIONS_H_
-
-#include <jni.h>
-
-#include "JavaClasses.h"
-
-namespace OIC
-{
- namespace Service
- {
- class RCSPlatformException;
- }
-}
-
-class JNIEnvWrapper;
-
-void initJavaExceptions(JNIEnvWrapper*);
-void clearJavaExceptions(JNIEnvWrapper*);
-
-void throwPlatformException(JNIEnv*, const OIC::Service::RCSPlatformException&);
-
-template < typename ENV >
-void throwRCSException(ENV* env, const char* msg)
-{
- //env->ThrowNew(env->FindClass(EXC_NAME_RCS), msg);
-}
-
-
-#endif // JAVA_EXCEPTIONS_H_
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-#ifndef JAVA_LOCAL_REF_H_
-#define JAVA_LOCAL_REF_H_
-
-#include <jni.h>
-#include <cassert>
-
-template < typename T >
-class JavaLocalRef
-{
-public:
- JavaLocalRef(JNIEnv *env, T obj) noexcept :
- m_env { env },
- m_obj { obj }
- {
- assert(env && "JNIEnv is nullptr");
- }
-
- template< typename ENV >
- JavaLocalRef(ENV *env, T obj) noexcept :
- m_env { env->get() },
- m_obj { obj }
- {
- assert(env && "JNIEnv is nullptr");
- }
-
- ~JavaLocalRef()
- {
- if (m_obj) m_env->DeleteLocalRef(m_obj);
- }
-
- operator bool() const noexcept { return m_obj; }
- operator T() const noexcept { return m_obj; }
-
- jobject get() const noexcept { return m_obj; }
-
- JavaLocalRef(const JavaLocalRef &) = delete;
- JavaLocalRef &operator=(const JavaLocalRef &) = delete;
-
- JavaLocalRef &operator=(JavaLocalRef && ) = delete;
-
-private:
- JNIEnv *m_env;
- T m_obj;
-};
-
-typedef JavaLocalRef< jobject > JavaLocalObject;
-typedef JavaLocalRef< jstring > JavaLocalString;
-typedef JavaLocalRef< jclass > JavaLocalClass;
-
-#endif // JAVA_LOCAL_REF_H_
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-#ifndef RCS_JNI_LOG_H
-#define RCS_JNI_LOG_H
-
-#include <android/log.h>
-
-#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
-#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
-#define LOGW(...) __android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__)
-#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
-
-#define LOGT_I(LOG_TAG, ...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
-#define LOGT_D(LOG_TAG, ...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
-#define LOGT_E(LOG_TAG, ...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
-
-#define EXPECT(EXP, MSG) do { if (!(EXP)) { LOGW(MSG); return; } } while(false)
-
-#define EXPECT_RET(EXP, MSG, RET_IF_FAILED) \
- do { if (!(EXP)) { LOGW(MSG); return RET_IF_FAILED; } } while(false)
-
-#define EXPECT_RET_DEF(EXP, MSG) EXPECT_RET(EXP, MSG, { })
-
-#endif // RCS_JNI_LOG_H
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-#ifndef RCS_JIN_SCOPEDENV_H_
-#define RCS_JIN_SCOPEDENV_H_
-
-#include <utility>
-
-#include <jni.h>
-
-#include "JNIEnvWrapper.h"
-#include "Log.h"
-
-extern JavaVM* g_jvm;
-
-namespace Detail
-{
- inline std::pair<JNIEnv*, bool> getEnv()
- {
- JNIEnv* env{ };
- bool needToDetach{ };
-
- auto ret = g_jvm->GetEnv((void**) &env, JNI_VERSION_1_6);
-
- switch (ret)
- {
- case JNI_OK:
- break;
-
- case JNI_EDETACHED:
- {
- auto attachRet = g_jvm->AttachCurrentThread(&env, NULL);
-
- if (attachRet != JNI_OK)
- {
- LOGT_E("JNI-ScopedEnv", "Failed to get the environment : %d", attachRet);
- }
- else
- {
- needToDetach = true;
- }
- break;
- }
- case JNI_EVERSION:
- LOGT_E("JNI-ScopedEnv", "JNI version not supported");
- break;
-
- default:
- LOGT_E("JNI-ScopedEnv", "Failed to get the environment");
- break;
- }
-
- return { env, needToDetach };
- }
-}
-
-class ScopedEnv
-{
-public:
- ScopedEnv() noexcept :
- m_env { },
- m_needToDetach{ false }
- {
- auto val = Detail::getEnv();
-
- m_env = val.first;
- m_needToDetach = val.second;
- }
-
- ~ScopedEnv()
- {
- if (m_env && m_needToDetach)
- {
- g_jvm->DetachCurrentThread();
- }
- }
-
- ScopedEnv(const ScopedEnv&) = delete;
- ScopedEnv& operator=(const ScopedEnv&) = delete;
-
- operator bool() const noexcept
- {
- return m_env;
- }
-
- JNIEnv* operator->() noexcept
- {
- return m_env;
- }
-
- JNIEnv* get() noexcept
- {
- return m_env;
- }
-
-private:
- JNIEnv* m_env;
- bool m_needToDetach;
-};
-
-class ScopedEnvWrapper
-{
-public:
- ScopedEnvWrapper() noexcept :
- m_env { },
- m_needToDetach{ false }
- {
- auto val = Detail::getEnv();
-
- m_env = val.first;
- m_needToDetach = val.second;
- }
-
- ~ScopedEnvWrapper()
- {
- if (m_env && m_needToDetach)
- {
- g_jvm->DetachCurrentThread();
- }
- }
-
- ScopedEnvWrapper(const ScopedEnvWrapper&) = delete;
- ScopedEnvWrapper& operator=(const ScopedEnvWrapper&) = delete;
-
- operator bool() const noexcept
- {
- return m_env;
- }
-
- JNIEnvWrapper* operator->() noexcept
- {
- return &m_env;
- }
-
- JNIEnvWrapper* get() noexcept
- {
- return &m_env;
- }
-
-private:
- JNIEnvWrapper m_env;
- bool m_needToDetach;
-};
-
-#endif // RCS_JIN_SCOPEDENV_H_
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-#ifndef RCS_JNI_VERIFY_H_
-#define RCS_JNI_VERIFY_H_
-
-#define VERIFY_NO_EXC(ENV) do { \
- if ((ENV)->ExceptionCheck()) { (ENV)->ExceptionDescribe(); return; } } while(false)
-
-#define VERIFY_NO_EXC_RET(ENV, RET) do { \
- if ((ENV)->ExceptionCheck()) { (ENV)->ExceptionDescribe(); return RET; } } while(false)
-
-#define VERIFY_NO_EXC_RET_DEF(ENV) VERIFY_NO_EXC_RET(ENV, { })
-
-#endif // RCS_JNI_VERIFY_H_
+++ /dev/null
-/*
- *******************************************************************
- *
- * Copyright 2015 Intel Corporation.
- *
- *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- *
- * 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 ':resource-container'
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<module external.linked.project.id="AndroidBundle" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$" external.system.id="GRADLE" external.system.module.group="" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
- <component name="FacetManager">
- <facet type="java-gradle" name="Java-Gradle">
- <configuration>
- <option name="BUILD_FOLDER_PATH" value="$MODULE_DIR$/build" />
- <option name="BUILDABLE" value="false" />
- </configuration>
- </facet>
- </component>
- <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_7" inherit-compiler-output="true">
- <exclude-output />
- <content url="file://$MODULE_DIR$">
- <excludeFolder url="file://$MODULE_DIR$/.gradle" />
- </content>
- <orderEntry type="inheritedJdk" />
- <orderEntry type="sourceFolder" forTests="false" />
- </component>
-</module>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<module external.linked.project.id=":app" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$/.." external.system.id="GRADLE" external.system.module.group="AndroidBundle" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
- <component name="FacetManager">
- <facet type="android-gradle" name="Android-Gradle">
- <configuration>
- <option name="GRADLE_PROJECT_PATH" value=":app" />
- </configuration>
- </facet>
- <facet type="android" name="Android">
- <configuration>
- <option name="SELECTED_BUILD_VARIANT" value="debug" />
- <option name="SELECTED_TEST_ARTIFACT" value="_android_test_" />
- <option name="ASSEMBLE_TASK_NAME" value="assembleDebug" />
- <option name="COMPILE_JAVA_TASK_NAME" value="compileDebugSources" />
- <option name="ASSEMBLE_TEST_TASK_NAME" value="assembleDebugAndroidTest" />
- <option name="COMPILE_JAVA_TEST_TASK_NAME" value="compileDebugAndroidTestSources" />
- <afterSyncTasks>
- <task>generateDebugAndroidTestSources</task>
- <task>generateDebugSources</task>
- </afterSyncTasks>
- <option name="ALLOW_USER_CONFIGURATION" value="false" />
- <option name="MANIFEST_FILE_RELATIVE_PATH" value="/src/main/AndroidManifest.xml" />
- <option name="RES_FOLDER_RELATIVE_PATH" value="/src/main/res" />
- <option name="RES_FOLDERS_RELATIVE_PATH" value="file://$MODULE_DIR$/src/main/res" />
- <option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" />
- </configuration>
- </facet>
- </component>
- <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_7" inherit-compiler-output="false">
- <output url="file://$MODULE_DIR$/build/intermediates/classes/debug" />
- <output-test url="file://$MODULE_DIR$/build/intermediates/classes/androidTest/debug" />
- <exclude-output />
- <content url="file://$MODULE_DIR$">
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/debug" isTestSource="false" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/debug" isTestSource="false" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/debug" isTestSource="false" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/debug" isTestSource="false" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/debug" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/resValues/debug" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/androidTest/debug" isTestSource="true" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/androidTest/debug" isTestSource="true" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/androidTest/debug" isTestSource="true" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/androidTest/debug" isTestSource="true" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/androidTest/debug" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/resValues/androidTest/debug" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/res" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/resources" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/assets" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/aidl" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/java" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/jni" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/rs" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/res" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/assets" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/aidl" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/jni" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/rs" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/res" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/resources" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/assets" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/aidl" isTestSource="true" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/java" isTestSource="true" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/jni" isTestSource="true" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/rs" isTestSource="true" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/assets" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/bundles" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/classes" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/coverage-instrumented-classes" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dependency-cache" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex-cache" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/exploded-aar/iotivity-armeabi-v7a-resource-container-release/jars" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/jacoco" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/javaResources" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/libs" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/lint" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/manifests" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/ndk" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/pre-dexed" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/proguard" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/res" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/rs" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/symbols" />
- <excludeFolder url="file://$MODULE_DIR$/build/outputs" />
- <excludeFolder url="file://$MODULE_DIR$/build/tmp" />
- </content>
- <orderEntry type="jdk" jdkName="Android API 23 Platform" jdkType="Android SDK" />
- <orderEntry type="sourceFolder" forTests="false" />
- <orderEntry type="library" exported="" name="iotivity-armeabi-v7a-resource-container-release-" level="project" />
- </component>
-</module>
\ No newline at end of file
+++ /dev/null
-apply plugin: 'com.android.library'
-
-android {
- compileSdkVersion 23
- buildToolsVersion "22.0.1"
-
- defaultConfig {
- minSdkVersion 21
- targetSdkVersion 23
- versionCode 1
- versionName "1.0"
- }
- buildTypes {
- release {
- minifyEnabled false
- proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
- }
- }
-}
-
-dependencies {
- compile fileTree(dir: 'libs', include: ['*.jar'])
- compile(name:'iotivity-armeabi-v7a-resource-container-release', ext:'aar')
-}
+++ /dev/null
-package org.iotivity.service.sample.androidbundle;
-
-import android.app.Application;
-import android.test.ApplicationTestCase;
-
-/**
- * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
- */
-public class ApplicationTest extends ApplicationTestCase<Application> {
- public ApplicationTest() {
- super(Application.class);
- }
-}
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="utf-8"?>
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="org.iotivity.service.sample.androidbundle" >
-
- <application
- android:allowBackup="true"
- android:icon="@mipmap/ic_launcher"
- android:label="@string/app_name"
- android:theme="@style/AppTheme" >
- <activity
- android:name=".DummyActivity"
- android:label="@string/app_name" >
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
-
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
- </application>
-
-</manifest>
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2015 Samsung Electronics All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-package org.iotivity.service.sample.androidbundle;
-
-import android.app.Activity;
-import android.os.Bundle;
-import android.view.Menu;
-import android.view.MenuItem;
-
-public class DummyActivity extends Activity {
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- }
-
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- // Inflate the menu; this adds items to the action bar if it is present.
- getMenuInflater().inflate(R.menu.menu_main, menu);
- return true;
- }
-
- @Override
- public boolean onOptionsItemSelected(MenuItem item) {
- // Handle action bar item clicks here. The action bar will
- // automatically handle clicks on the Home/Up button, so long
- // as you specify a parent activity in AndroidManifest.xml.
- int id = item.getItemId();
-
- //noinspection SimplifiableIfStatement
- if (id == R.id.action_settings) {
- return true;
- }
-
- return super.onOptionsItemSelected(item);
- }
-}
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2015 Samsung Electronics All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-package org.iotivity.service.sample.androidbundle;
-
-import android.content.Context;
-import android.util.Log;
-
-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;
-
-import java.util.List;
-import java.util.Vector;
-
-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 " + bundleAPI
- + "," + appContext);
- }
-
- @Override
- public void activateBundle() {
- Log.d(SampleActivator.class.getName(), "Activate bundle called");
-
- 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");
- }
- 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() {
- Log.d(SampleActivator.class.getName(), "De-activate bundle called.");
- for(BundleResource resource : resources){
- bundleAPI.unregisterResource(resource);
- }
- }
-
- @Override
- public void createResource(ResourceConfig config) {
- BundleResource 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.gyroscope".equals(config.getResourceType())){
- resource =
- new GyroscopeResource(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);
- }
- }
-
- @Override
- public void destroyResource(BundleResource androidBundleResource) {
- Log.d(SampleActivator.class.getName(), "Destroy resource called.");
- bundleAPI.unregisterResource(androidBundleResource);
- }
-}
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2015 Samsung Electronics All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-package 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.BundleSoftSensorResource;
-import org.iotivity.service.resourcecontainer.RcsResourceAttributes;
-import org.iotivity.service.resourcecontainer.RcsValue;
-
-import java.util.HashMap;
-import java.util.Vector;
-
-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);
- }
-
- @Override
- protected void onUpdatedInputResource(String attributeName, Vector<RcsValue> values) {
- m_mapInputData.put(attributeName, values.get(0));
- executeLogic();
- }
-
- @Override
- protected void executeLogic() {
- if(m_mapInputData.get("humidity") != null && m_mapInputData.get("temperature") != null){
- 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;
-
- // calculation of discomfortIndex
- dDI = F - (F - 58.0) * (double)((100 - h) * 55) / 10000.0;
-
- this.setAttribute("temperature", new RcsValue(t));
- 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") );
- }
- }
-
- @Override
- public void handleSetAttributesRequest(RcsResourceAttributes rcsResourceAttributes) {
- this.setAttributes(rcsResourceAttributes);
- executeLogic();
- }
-
- @Override
- 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, "*************************************** ");
- }
-}
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2015 Samsung Electronics All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-package org.iotivity.service.sample.androidbundle.resources;
-
-import android.content.Context;
-import android.hardware.Sensor;
-import android.hardware.SensorEvent;
-import android.hardware.SensorEventListener;
-import android.hardware.SensorManager;
-import android.util.Log;
-
-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 BundleResource implements SensorEventListener {
- private static final String LOG_TAG = GyroscopeResource.class.getSimpleName();
- private final SensorManager mSensorManager;
- private final Sensor humiditySensor;
-
- public GyroscopeResource(Context context){
- super(context);
- this.setResourceType("oic.r.gyroscope");
- this.setName("gyroscopeSensor");
- 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");
- }
-
- @Override
- protected void initAttributes() {
- this.m_attributes.put("x", 0d);
- this.m_attributes.put("y", 0d);
- this.m_attributes.put("z", 0d);
- }
-
- @Override
- public void handleSetAttributesRequest(RcsResourceAttributes attrs) {
- Log.i(LOG_TAG, "Set Attributes called with ");
- for(String key: attrs.keySet()){
- Log.i(LOG_TAG, " " + key + ": " + attrs.get(key));
- }
- }
-
- @Override
- public RcsResourceAttributes handleGetAttributesRequest() {
- Log.i(LOG_TAG, "Get Attributes called");
- Log.i(LOG_TAG, "Returning: ");
- for(String key:m_attributes.keySet()){
- Log.i(LOG_TAG, " " + key + ": " + m_attributes.get(key));
- }
- return this.m_attributes;
- }
-
- @Override
- public void onSensorChanged(SensorEvent sensorEvent) {
- Log.i(LOG_TAG, "Sensor event " + sensorEvent.values[0] + ", " + sensorEvent.values[1]
- + ", " + sensorEvent.values[2]);
- setAttribute("x", new RcsValue( (int) (sensorEvent.values[0])), true);
- setAttribute("y", new RcsValue( (int) (sensorEvent.values[1]) ) , true);
- setAttribute("z", new RcsValue( (int) (sensorEvent.values[2]) ) , true);
- }
-
- @Override
- public void onAccuracyChanged(Sensor sensor, int i) {
-
- }
-}
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2015 Samsung Electronics All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-package org.iotivity.service.sample.androidbundle.resources;
-
-import android.content.Context;
-import android.hardware.Sensor;
-import android.hardware.SensorEvent;
-import android.hardware.SensorEventListener;
-import android.hardware.SensorManager;
-import android.util.Log;
-
-import org.iotivity.service.resourcecontainer.BundleResource;
-import org.iotivity.service.resourcecontainer.RcsResourceAttributes;
-import org.iotivity.service.resourcecontainer.RcsValue;
-
-public class HumidityResource extends BundleResource implements SensorEventListener {
- private static final String LOG_TAG = HumidityResource.class.getSimpleName();
- private final SensorManager mSensorManager;
- private final Sensor humiditySensor;
-
- public HumidityResource(Context context){
- super(context);
- this.setResourceType("oic.r.humidity");
- this.setName("humiditySensor");
- mSensorManager = (SensorManager) context.getApplicationContext().
- getSystemService(Context.SENSOR_SERVICE);
- humiditySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
- mSensorManager.registerListener(this, humiditySensor, SensorManager.SENSOR_DELAY_NORMAL);
- }
-
- @Override
- protected void initAttributes() {
- this.m_attributes.put("humidity", 0d);
- }
-
- @Override
- public void handleSetAttributesRequest(RcsResourceAttributes attrs) {
- Log.i(LOG_TAG, "Set Attributes called with ");
- for(String key: attrs.keySet()){
- Log.i(LOG_TAG, " " + key + ": " + attrs.get(key));
- }
- }
-
- @Override
- public RcsResourceAttributes handleGetAttributesRequest() {
- Log.i(LOG_TAG, "Get Attributes called");
- Log.i(LOG_TAG, "Returning: ");
- for(String key: m_attributes.keySet()){
- Log.i(LOG_TAG, " " + key + ": " + m_attributes.get(key));
- }
- return this.m_attributes;
- }
-
- @Override
- public void onSensorChanged(SensorEvent sensorEvent) {
- Log.i(LOG_TAG, "Sensor event " + sensorEvent.values[0]);
-
- setAttribute("humidity", new RcsValue( (int) (sensorEvent.values[0]) ) , true);
- }
-
- @Override
- public void onAccuracyChanged(Sensor sensor, int i) {
-
- }
-}
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2015 Samsung Electronics All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-package org.iotivity.service.sample.androidbundle.resources;
-
-import android.content.Context;
-import android.hardware.Sensor;
-import android.hardware.SensorEvent;
-import android.hardware.SensorEventListener;
-import android.hardware.SensorManager;
-import android.util.Log;
-
-import org.iotivity.service.resourcecontainer.BundleResource;
-import org.iotivity.service.resourcecontainer.RcsResourceAttributes;
-import org.iotivity.service.resourcecontainer.RcsValue;
-
-public class LightIntensityResource extends BundleResource implements SensorEventListener {
- private static final String LOG_TAG = LightIntensityResource.class.getSimpleName();
- private final SensorManager mSensorManager;
- private final Sensor lightSensor;
-
- public LightIntensityResource(Context context){
- super(context);
- this.setResourceType("oic.r.lightsensor");
- this.setName("lightSensor");
- mSensorManager = (SensorManager) context.getApplicationContext().
- getSystemService(Context.SENSOR_SERVICE);
- lightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
- mSensorManager.registerListener(this, lightSensor, SensorManager.SENSOR_DELAY_NORMAL);
- }
-
- @Override
- protected void initAttributes() {
- this.m_attributes.put("intensity", 0);
- }
-
- @Override
- public void handleSetAttributesRequest(RcsResourceAttributes attrs) {
- Log.i(LOG_TAG, "Set Attributes called with ");
- for(String key: attrs.keySet()){
- Log.i(LOG_TAG, " " + key + ": " + attrs.get(key));
- }
- }
-
- @Override
- public RcsResourceAttributes handleGetAttributesRequest() {
- Log.i(LOG_TAG, "Get Attributes called");
- Log.i(LOG_TAG, "Returning: ");
- for(String key: m_attributes.keySet()){
- Log.i(LOG_TAG, " " + key + ": " + m_attributes.get(key));
- }
- return this.m_attributes;
- }
-
- @Override
- public void onSensorChanged(SensorEvent sensorEvent) {
- Log.i(LOG_TAG, "Sensor event " + sensorEvent.values[0]);
-
- setAttribute("intensity", new RcsValue( (int) (sensorEvent.values[0]) ) , true);
- }
-
- @Override
- public void onAccuracyChanged(Sensor sensor, int i) {
-
- }
-}
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2015 Samsung Electronics All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-package org.iotivity.service.sample.androidbundle.resources;
-
-import android.content.Context;
-import android.hardware.Sensor;
-import android.hardware.SensorEvent;
-import android.hardware.SensorEventListener;
-import android.hardware.SensorManager;
-import android.util.Log;
-
-import org.iotivity.service.resourcecontainer.BundleResource;
-import org.iotivity.service.resourcecontainer.RcsResourceAttributes;
-import org.iotivity.service.resourcecontainer.RcsValue;
-
-public class TemperatureResource extends BundleResource implements SensorEventListener {
- private static final String LOG_TAG = HumidityResource.class.getSimpleName();
- private final SensorManager mSensorManager;
- private final Sensor temperatureSensor;
-
- public TemperatureResource(Context context){
- super(context);
- this.setResourceType("oic.r.temperature");
- this.setName("temperatureSensor");
- mSensorManager = (SensorManager) context.getApplicationContext().
- getSystemService(Context.SENSOR_SERVICE);
- temperatureSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE);
- mSensorManager.registerListener(this, temperatureSensor, SensorManager.SENSOR_DELAY_NORMAL);
- }
-
- @Override
- protected void initAttributes() {
- this.m_attributes.put("temperature", 0d);
- }
-
- @Override
- public void handleSetAttributesRequest(RcsResourceAttributes attrs) {
- Log.i(LOG_TAG, "Set Attributes called with ");
- for(String key: attrs.keySet()){
- Log.i(LOG_TAG, " " + key + ": " + attrs.get(key));
- }
- }
-
- @Override
- public RcsResourceAttributes handleGetAttributesRequest() {
- Log.i(LOG_TAG, "Get Attributes called");
- Log.i(LOG_TAG, "Returning: ");
- for(String key: m_attributes.keySet()){
- Log.i(LOG_TAG, " " + key + ": " + m_attributes.get(key));
- }
- return this.m_attributes;
- }
-
- @Override
- public void onSensorChanged(SensorEvent sensorEvent) {
- Log.i(LOG_TAG, "Sensor event " + sensorEvent.values[0]);
-
- setAttribute("temperature", new RcsValue( (int) (sensorEvent.values[0]) ) , true);
- }
-
- @Override
- public void onAccuracyChanged(Sensor sensor, int i) {
-
- }
-}
+++ /dev/null
-<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
- android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
- android:paddingRight="@dimen/activity_horizontal_margin"
- android:paddingTop="@dimen/activity_vertical_margin"
- android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
-
- <TextView android:text="@string/hello_world" android:layout_width="wrap_content"
- android:layout_height="wrap_content" />
-
-</RelativeLayout>
+++ /dev/null
-<menu xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools" tools:context=".MainActivity">
- <item android:id="@+id/action_settings" android:title="@string/action_settings"
- android:orderInCategory="100" android:showAsAction="never" />
-</menu>
+++ /dev/null
-<?xml version="1.0" encoding="utf-8"?>
-<resources>
- <style name="AppTheme" parent="android:Theme.Material.Light">
- </style>
-</resources>
+++ /dev/null
-<resources>
- <!-- Example customization of dimensions originally defined in res/values/dimens.xml
- (such as screen margins) for screens with more than 820dp of available width. This
- would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively). -->
- <dimen name="activity_horizontal_margin">64dp</dimen>
-</resources>
+++ /dev/null
-<resources>
- <!-- Default screen margins, per the Android Design guidelines. -->
- <dimen name="activity_horizontal_margin">16dp</dimen>
- <dimen name="activity_vertical_margin">16dp</dimen>
-</resources>
+++ /dev/null
-<resources>
- <string name="app_name">AndroidBundle</string>
-
- <string name="hello_world">Hello world!</string>
- <string name="action_settings">Settings</string>
-</resources>
+++ /dev/null
-<resources>
-
- <!-- Base application theme. -->
- <style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
- <!-- Customize your theme here. -->
- </style>
-
-</resources>
+++ /dev/null
-// Top-level build file where you can add configuration options common to all sub-projects/modules.
-
-buildscript {
- repositories {
- jcenter()
- }
- dependencies {
- classpath 'com.android.tools.build:gradle:1.3.0'
-
- // NOTE: Do not place your application dependencies here; they belong
- // in the individual module build.gradle files
- }
-}
-
-allprojects {
- repositories {
- maven { url 'http://jcenter.bintray.com/' }
- flatDir { dirs 'libs' }
- }
-}
+++ /dev/null
-#Sun Nov 08 19:01:42 KST 2015
-distributionBase=GRADLE_USER_HOME
-distributionPath=wrapper/dists
-zipStoreBase=GRADLE_USER_HOME
-zipStorePath=wrapper/dists
-distributionUrl=https\://services.gradle.org/distributions/gradle-2.4-all.zip
+++ /dev/null
-#!/usr/bin/env bash
-
-##############################################################################
-##
-## Gradle start up script for UN*X
-##
-##############################################################################
-
-# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
-DEFAULT_JVM_OPTS=""
-
-APP_NAME="Gradle"
-APP_BASE_NAME=`basename "$0"`
-
-# Use the maximum available, or set MAX_FD != -1 to use that value.
-MAX_FD="maximum"
-
-warn ( ) {
- echo "$*"
-}
-
-die ( ) {
- echo
- echo "$*"
- echo
- exit 1
-}
-
-# OS specific support (must be 'true' or 'false').
-cygwin=false
-msys=false
-darwin=false
-case "`uname`" in
- CYGWIN* )
- cygwin=true
- ;;
- Darwin* )
- darwin=true
- ;;
- MINGW* )
- msys=true
- ;;
-esac
-
-# For Cygwin, ensure paths are in UNIX format before anything is touched.
-if $cygwin ; then
- [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
-fi
-
-# Attempt to set APP_HOME
-# Resolve links: $0 may be a link
-PRG="$0"
-# Need this for relative symlinks.
-while [ -h "$PRG" ] ; do
- ls=`ls -ld "$PRG"`
- link=`expr "$ls" : '.*-> \(.*\)$'`
- if expr "$link" : '/.*' > /dev/null; then
- PRG="$link"
- else
- PRG=`dirname "$PRG"`"/$link"
- fi
-done
-SAVED="`pwd`"
-cd "`dirname \"$PRG\"`/" >&-
-APP_HOME="`pwd -P`"
-cd "$SAVED" >&-
-
-CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
-
-# Determine the Java command to use to start the JVM.
-if [ -n "$JAVA_HOME" ] ; then
- if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
- # IBM's JDK on AIX uses strange locations for the executables
- JAVACMD="$JAVA_HOME/jre/sh/java"
- else
- JAVACMD="$JAVA_HOME/bin/java"
- fi
- if [ ! -x "$JAVACMD" ] ; then
- die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
-
-Please set the JAVA_HOME variable in your environment to match the
-location of your Java installation."
- fi
-else
- JAVACMD="java"
- which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
-
-Please set the JAVA_HOME variable in your environment to match the
-location of your Java installation."
-fi
-
-# Increase the maximum file descriptors if we can.
-if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
- MAX_FD_LIMIT=`ulimit -H -n`
- if [ $? -eq 0 ] ; then
- if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
- MAX_FD="$MAX_FD_LIMIT"
- fi
- ulimit -n $MAX_FD
- if [ $? -ne 0 ] ; then
- warn "Could not set maximum file descriptor limit: $MAX_FD"
- fi
- else
- warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
- fi
-fi
-
-# For Darwin, add options to specify how the application appears in the dock
-if $darwin; then
- GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
-fi
-
-# For Cygwin, switch paths to Windows format before running java
-if $cygwin ; then
- APP_HOME=`cygpath --path --mixed "$APP_HOME"`
- CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
-
- # We build the pattern for arguments to be converted via cygpath
- ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
- SEP=""
- for dir in $ROOTDIRSRAW ; do
- ROOTDIRS="$ROOTDIRS$SEP$dir"
- SEP="|"
- done
- OURCYGPATTERN="(^($ROOTDIRS))"
- # Add a user-defined pattern to the cygpath arguments
- if [ "$GRADLE_CYGPATTERN" != "" ] ; then
- OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
- fi
- # Now convert the arguments - kludge to limit ourselves to /bin/sh
- i=0
- for arg in "$@" ; do
- CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
- CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
-
- if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
- eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
- else
- eval `echo args$i`="\"$arg\""
- fi
- i=$((i+1))
- done
- case $i in
- (0) set -- ;;
- (1) set -- "$args0" ;;
- (2) set -- "$args0" "$args1" ;;
- (3) set -- "$args0" "$args1" "$args2" ;;
- (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
- (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
- (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
- (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
- (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
- (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
- esac
-fi
-
-# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
-function splitJvmOpts() {
- JVM_OPTS=("$@")
-}
-eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
-JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
-
-exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
+++ /dev/null
-@if "%DEBUG%" == "" @echo off
-@rem ##########################################################################
-@rem
-@rem Gradle startup script for Windows
-@rem
-@rem ##########################################################################
-
-@rem Set local scope for the variables with windows NT shell
-if "%OS%"=="Windows_NT" setlocal
-
-@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
-set DEFAULT_JVM_OPTS=
-
-set DIRNAME=%~dp0
-if "%DIRNAME%" == "" set DIRNAME=.
-set APP_BASE_NAME=%~n0
-set APP_HOME=%DIRNAME%
-
-@rem Find java.exe
-if defined JAVA_HOME goto findJavaFromJavaHome
-
-set JAVA_EXE=java.exe
-%JAVA_EXE% -version >NUL 2>&1
-if "%ERRORLEVEL%" == "0" goto init
-
-echo.
-echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
-echo.
-echo Please set the JAVA_HOME variable in your environment to match the
-echo location of your Java installation.
-
-goto fail
-
-:findJavaFromJavaHome
-set JAVA_HOME=%JAVA_HOME:"=%
-set JAVA_EXE=%JAVA_HOME%/bin/java.exe
-
-if exist "%JAVA_EXE%" goto init
-
-echo.
-echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
-echo.
-echo Please set the JAVA_HOME variable in your environment to match the
-echo location of your Java installation.
-
-goto fail
-
-:init
-@rem Get command-line arguments, handling Windowz variants
-
-if not "%OS%" == "Windows_NT" goto win9xME_args
-if "%@eval[2+2]" == "4" goto 4NT_args
-
-:win9xME_args
-@rem Slurp the command line arguments.
-set CMD_LINE_ARGS=
-set _SKIP=2
-
-:win9xME_args_slurp
-if "x%~1" == "x" goto execute
-
-set CMD_LINE_ARGS=%*
-goto execute
-
-:4NT_args
-@rem Get arguments from the 4NT Shell from JP Software
-set CMD_LINE_ARGS=%$
-
-:execute
-@rem Setup the command line
-
-set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
-
-@rem Execute Gradle
-"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
-
-:end
-@rem End local scope for the variables with windows NT shell
-if "%ERRORLEVEL%"=="0" goto mainEnd
-
-:fail
-rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
-rem the _cmd.exe /c_ return code!
-if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
-exit /b 1
-
-:mainEnd
-if "%OS%"=="Windows_NT" endlocal
-
-:omega
+++ /dev/null
-include ':app'
+++ /dev/null
-To build the app
-
-1. build Iotivity with TARGET_OS=android
-
-2. Copy aar files into app/libs folder
- - {Iotivity_root}/android/android_api/base/build/outputs/aar/iotivity-{TARGET_ARCH}-base-{MODE}.aar
- - {Iotivity_root}/service/resource-encapsulation/android/service/build/outputs/aar/iotivity-{TARGET_ARCH}-service-{MODE}.aar
-
-3. Configure dependencies for libs in app/build.gradle
- - default TARGET_ARCH is armeabi
- - default MODE is release
-
- for example, if you build Iotivity as follows,
-
- $scons TARGET_OS=android TARGET_ARCH=x86 RELEASE=0
-
- then, dependencies should be modified like below
-
- dependencies {
- compile(name:'iotivity-x86-service-debug', ext:'aar')
- compile(name:'iotivity-x86-base-debug', ext:'aar')
- }
-
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<module external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$/.." external.system.id="GRADLE" type="JAVA_MODULE" version="4">
- <component name="FacetManager">
- <facet type="android-gradle" name="Android-Gradle">
- <configuration>
- <option name="GRADLE_PROJECT_PATH" value=":app" />
- </configuration>
- </facet>
- <facet type="android" name="Android">
- <configuration>
- <option name="SELECTED_BUILD_VARIANT" value="debug" />
- <option name="ASSEMBLE_TASK_NAME" value="assembleDebug" />
- <option name="COMPILE_JAVA_TASK_NAME" value="compileDebugSources" />
- <option name="ASSEMBLE_TEST_TASK_NAME" value="assembleDebugTest" />
- <option name="SOURCE_GEN_TASK_NAME" value="generateDebugSources" />
- <option name="TEST_SOURCE_GEN_TASK_NAME" value="generateDebugTestSources" />
- <option name="ALLOW_USER_CONFIGURATION" value="false" />
- <option name="MANIFEST_FILE_RELATIVE_PATH" value="/src/main/AndroidManifest.xml" />
- <option name="RES_FOLDER_RELATIVE_PATH" value="/src/main/res" />
- <option name="RES_FOLDERS_RELATIVE_PATH" value="file://$MODULE_DIR$/src/main/res" />
- <option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" />
- </configuration>
- </facet>
- </component>
- <component name="NewModuleRootManager" inherit-compiler-output="false">
- <output url="file://$MODULE_DIR$/build/intermediates/classes/debug" />
- <exclude-output />
- <content url="file://$MODULE_DIR$">
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/debug" isTestSource="false" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/debug" isTestSource="false" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/debug" isTestSource="false" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/debug" isTestSource="false" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/debug" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/debug" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/test/debug" isTestSource="true" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/test/debug" isTestSource="true" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/test/debug" isTestSource="true" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/test/debug" isTestSource="true" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/test/debug" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/test/debug" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/res" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/resources" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/assets" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/aidl" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/java" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/jni" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/rs" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/res" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/assets" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/aidl" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/jni" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/rs" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/res" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/resources" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/assets" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/aidl" isTestSource="true" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/java" isTestSource="true" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/jni" isTestSource="true" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/rs" isTestSource="true" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/assets" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/bundles" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/classes" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/coverage-instrumented-classes" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dependency-cache" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex-cache" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/jacoco" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/javaResources" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/libs" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/lint" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/manifests" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/ndk" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/pre-dexed" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/proguard" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/res" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/rs" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/symbols" />
- <excludeFolder url="file://$MODULE_DIR$/build/outputs" />
- <excludeFolder url="file://$MODULE_DIR$/build/tmp" />
- </content>
- <orderEntry type="jdk" jdkName="Android API 21 Platform" jdkType="Android SDK" />
- <orderEntry type="sourceFolder" forTests="false" />
- <orderEntry type="library" exported="" name="iotivity-service-release-" level="project" />
- <orderEntry type="library" exported="" name="iotivity-base-release-" level="project" />
- </component>
-</module>
-
+++ /dev/null
-apply plugin: 'com.android.application'
-
-android {
- compileSdkVersion 21
- buildToolsVersion "20.0.0"
-
- defaultConfig {
- applicationId "org.iotivity.service.sample.client"
- minSdkVersion 21
- targetSdkVersion 21
- versionCode 1
- versionName "1.0"
- }
- buildTypes {
- release {
- minifyEnabled false
- proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
- }
- }
-}
-
-dependencies {
- compile fileTree(include: ['*.jar'], dir: 'libs')
- compile(name:'iotivity-service-release', ext:'aar')
- compile(name:'iotivity-base-release', ext:'aar')
-}
+++ /dev/null
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="org.iotivity.service.sample.client">
-
- <uses-permission android:name="android.permission.INTERNET" />
- <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
-
- <application android:allowBackup="true" android:label="@string/app_name"
- android:icon="@mipmap/ic_launcher" android:theme="@style/AppTheme">
- <activity
- android:name=".ContainerClientActivity"
- android:label="@string/app_name" >
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
-
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
- <!-- <activity android:name=".ContainerClientActivity" /> -->
- </application>
-
-</manifest>
+++ /dev/null
-/******************************************************************
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- * <p>
- * <p>
- * <p>
- * 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
- * <p>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p>
- * 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.iotivity.service.sample.client;
-
-import android.app.Activity;
-import android.os.Bundle;
-import android.os.Handler;
-import android.os.Message;
-import android.util.Log;
-import android.view.View;
-import android.widget.ListView;
-import android.widget.TextView;
-
-import org.iotivity.service.RcsException;
-import org.iotivity.service.client.RcsAddress;
-import org.iotivity.service.client.RcsDiscoveryManager;
-import org.iotivity.service.client.RcsRemoteResourceObject;
-
-import java.lang.ref.WeakReference;
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * It contains the discover resource API for Discovering Container Resource
- */
-
-public class ContainerClientActivity extends Activity implements
- RcsDiscoveryManager.OnResourceDiscoveredListener {
- public static final int MSG_ID_ATTRIBUTE_RECEIVED = 0;
- public static final int MSG_ID_CACHEDATA_RECEIVED = 1;
-
- private final String LOG_TAG = "[SampleClient] "
- + this.getClass().getSimpleName();
- private final String RESOURCE_DISCOVERY_URI_KEYWORD = "discomfort";
-
- private Handler mHandler;
-
- private ResourceListAdapter mResourceListViewAdapter;
-
- private ListView mResourceListView;
- private TextView mLogView;
-
- private List<String> mFoundResourceUris;
- private List<ResourceListItem> mFoundResources;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_container_client);
-
- mFoundResourceUris = new ArrayList<String>();
- mFoundResources = new ArrayList<ResourceListItem>();
-
- mHandler = new ContainerClientHandler(this);
-
- mResourceListViewAdapter = new ResourceListAdapter(this, R.layout.discovered_resource, mFoundResources);
- mResourceListView = (ListView) findViewById(R.id.ResourceListView);
- mResourceListView.setAdapter(mResourceListViewAdapter);
-
- mLogView = (TextView) findViewById(R.id.log);
- }
-
- public void onDiscoverResourceClick(View v) {
- try {
- RcsDiscoveryManager.getInstance().discoverResource(
- RcsAddress.multicast(),
- ContainerClientActivity.this);
-
- mFoundResourceUris.clear();
- mFoundResources.clear();
- mResourceListViewAdapter.notifyDataSetChanged();
-
- mLogView.setText("");
- } catch (RcsException e) {
- e.printStackTrace();
- }
- }
-
- private boolean IsFoundResource(String resourceUri)
- {
- if (mFoundResourceUris.contains(resourceUri))
- return true;
-
- return false;
- }
-
- @Override
- public void onResourceDiscovered(
- final RcsRemoteResourceObject discoveredResource) {
-
- runOnUiThread(new Runnable() {
- public void run() {
- try {
- String uri = discoveredResource.getUri();
- Log.i(LOG_TAG, "onResourceDiscovered -- " + uri);
-
- if (uri.contains(RESOURCE_DISCOVERY_URI_KEYWORD) && !IsFoundResource(uri)) {
- mFoundResourceUris.add(uri);
- mFoundResources.add(new ResourceListItem(uri, discoveredResource, ContainerClientActivity.this.getHandler()));
- mResourceListViewAdapter.notifyDataSetChanged();
- }
- } catch (RcsException e) {
- e.printStackTrace();
- }
- }
- });
- }
-
- private void printLog(String message) {
- Log.i(LOG_TAG, message);
- mLogView.setText(message);
- }
-
- public Handler getHandler() {
- return mHandler;
- }
-
- private static class ContainerClientHandler extends Handler {
- private WeakReference<ContainerClientActivity> mActivityRef;
- private String logMsg;
-
- private ContainerClientHandler(ContainerClientActivity activity) {
- mActivityRef = new WeakReference<>(activity);
- }
-
- @Override
- public void handleMessage(Message msg) {
- super.handleMessage(msg);
-
- ContainerClientActivity activity = mActivityRef.get();
- if (activity == null) return;
-
- switch (msg.what) {
- case MSG_ID_ATTRIBUTE_RECEIVED:
- logMsg = "-- ATTRIBUTE_RECEIVED\n";
- logMsg += msg.obj.toString();
- break;
-
- case MSG_ID_CACHEDATA_RECEIVED:
- logMsg = "-- CACHEDATA_RECEIVED\n";
- logMsg += msg.obj.toString();
- break;
- }
- activity.printLog(logMsg);
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-/******************************************************************
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- * <p>
- * <p>
- * <p>
- * 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
- * <p>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p>
- * 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.iotivity.service.sample.client;
-
-import android.app.Activity;
-import android.content.Context;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.ArrayAdapter;
-import android.widget.Button;
-import android.widget.TextView;
-import android.widget.ToggleButton;
-
-import org.iotivity.service.RcsException;
-
-import java.util.List;
-
-public class ResourceListAdapter extends ArrayAdapter<ResourceListItem> {
-
- private Context mContext;
- private int mLayoutId;
- private List<ResourceListItem> foundResources;
-
- public ResourceListAdapter(Context context, int layoutId, List<ResourceListItem> foundResources)
- {
- super(context, layoutId, foundResources);
-
- this.mLayoutId = layoutId;
- this.mContext = context;
- this.foundResources = foundResources;
- }
-
- @Override
- public View getView(final int position, View convertView, final ViewGroup parent) {
- if (convertView == null)
- {
- LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
- convertView = inflater.inflate(mLayoutId, parent, false);
- }
-
- String resourceUri = foundResources.get(position).mResourceUri;
-
- TextView textViewUri = (TextView) convertView.findViewById(R.id.textView_uri);
- textViewUri.setText(resourceUri);
-
- textViewUri.setOnClickListener(new View.OnClickListener() {
-
- @Override
- public void onClick(View view) {
- try {
- TextView textView = (TextView) ((Activity) mContext).findViewById(R.id.log);
- textView.setText(Utils.resourceInfo(foundResources.get(position).mResource));
- } catch (RcsException e) {
- e.printStackTrace();
- }
- }
- });
-
- Button buttonGet = (Button) convertView.findViewById(R.id.button_get);
- buttonGet.setOnClickListener(new View.OnClickListener() {
-
- @Override
- public void onClick(View view) {
- ResourceListItem selectedResource = foundResources.get(position);
- try {
- TextView textView = (TextView) ((Activity) mContext).findViewById(R.id.log);
- textView.setText("Get Remote Attributes from \'" + selectedResource.mResourceUri + "\'");
- selectedResource.mResource.getRemoteAttributes(selectedResource.mGetListener);
- } catch (RcsException e) {
- e.printStackTrace();
- }
- }
- });
-
- ToggleButton buttonObserve = (ToggleButton) convertView.findViewById(R.id.button_observe);
- buttonObserve.setOnClickListener(new View.OnClickListener() {
-
- @Override
- public void onClick(View view) {
- ResourceListItem selectedResource = foundResources.get(position);
- TextView textView = (TextView) ((Activity) mContext).findViewById(R.id.log);
-
- try {
- if (!selectedResource.mCacheStarted) {
- textView.setText("Start Observe \'" + selectedResource.mResourceUri + "\'");
- selectedResource.mResource.startCaching(selectedResource.mCacheListener);
- selectedResource.mCacheStarted = true;
- ((ToggleButton) view).setChecked(true);
- } else {
- textView.setText("Stop Observing \'" + selectedResource.mResourceUri + "\'");
- selectedResource.mResource.stopCaching();
- selectedResource.mCacheStarted = false;
- ((ToggleButton) view).setChecked(false);
- }
- } catch (RcsException e) {
- e.printStackTrace();
- }
- }
- });
-
- return convertView;
- }
-}
\ No newline at end of file
+++ /dev/null
-/******************************************************************
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- * <p>
- * <p>
- * <p>
- * 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
- * <p>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p>
- * 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.iotivity.service.sample.client;
-
-import android.os.Handler;
-import android.util.Log;
-
-import org.iotivity.service.RcsException;
-import org.iotivity.service.RcsResourceAttributes;
-import org.iotivity.service.client.RcsRemoteResourceObject;
-
-public class ResourceListItem {
- private final String LOG_TAG = "[RCSampleClient] "
- + this.getClass().getSimpleName();
-
- public String mResourceUri;
- public RcsRemoteResourceObject mResource;
- public RemoteResourceGetListener mGetListener;
- public RemoteResourceCacheListener mCacheListener;
- public boolean mCacheStarted;
-
- private Handler mHandler;
-
- public ResourceListItem(String resourceUri, RcsRemoteResourceObject resource, Handler handler)
- {
- mResourceUri = resourceUri;
- mResource = resource;
-
- mGetListener = new RemoteResourceGetListener();
- mCacheListener = new RemoteResourceCacheListener();
- mCacheStarted = false;
-
- mHandler = handler;
- }
-
- private class RemoteResourceGetListener implements RcsRemoteResourceObject.OnRemoteAttributesReceivedListener
- {
-
- @Override
- public void onAttributesReceived(final RcsResourceAttributes rcsResourceAttributes, int eCode) {
- Log.i(LOG_TAG, "onAttributesReceived -- " + mResourceUri);
-
- new Thread(new Runnable() {
-
- @Override
- public void run() {
- try {
- String logMessage;
- logMessage = "-- " + mResourceUri + "\n";
- logMessage += Utils.resourceAttributes(rcsResourceAttributes);
-
- mHandler.obtainMessage(ContainerClientActivity.MSG_ID_ATTRIBUTE_RECEIVED, logMessage).sendToTarget();
- } catch (RcsException e) {
- e.printStackTrace();
- }
- }
- }).run();
- }
- }
-
- private class RemoteResourceCacheListener implements RcsRemoteResourceObject.OnCacheUpdatedListener
- {
-
- @Override
- public void onCacheUpdated(final RcsResourceAttributes rcsResourceAttributes) {
- Log.i(LOG_TAG, "onCacheUpdated -- " + mResourceUri);
-
- new Thread(new Runnable() {
-
- @Override
- public void run() {
- try {
- String logMessage;
- logMessage = "-- " + mResourceUri + "\n";
- logMessage += Utils.resourceAttributes(rcsResourceAttributes);
-
- mHandler.obtainMessage(ContainerClientActivity.MSG_ID_CACHEDATA_RECEIVED, logMessage).sendToTarget();
- } catch (RcsException e) {
- e.printStackTrace();
- }
- }
- }).run();
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-/******************************************************************
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- * <p>
- * <p>
- * <p>
- * 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
- * <p>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p>
- * 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.iotivity.service.sample.client;
-
-import org.iotivity.service.RcsException;
-import org.iotivity.service.RcsResourceAttributes;
-import org.iotivity.service.client.RcsRemoteResourceObject;
-
-public class Utils {
- public static String resourceInfo(RcsRemoteResourceObject resourceObject)
- throws RcsException {
- StringBuilder sb = new StringBuilder();
-
- sb.append("URI : " + resourceObject.getUri() + "\n");
- sb.append("Host : " + resourceObject.getAddress() + "\n");
- for (String type : resourceObject.getTypes()) {
- sb.append("resourceType : " + type + "\n");
- }
-
- for (String itf : resourceObject.getInterfaces()) {
- sb.append("resourceInterfaces : " + itf + "\n");
- }
-
- sb.append("isObservable : " + resourceObject.isObservable() + "\n");
-
- return sb.toString();
- }
-
- public static String resourceAttributes(RcsResourceAttributes attr)
- throws RcsException {
- StringBuilder sb = new StringBuilder();
-
- for (String key : attr.keySet())
- {
- sb.append(key + " : " + attr.get(key) + "\n");
- }
-
- return sb.toString();
- }
-}
+++ /dev/null
-<?xml version="1.0" encoding="utf-8"?>
-<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical"
- android:id="@+id/main"
- android:weightSum="1"
- android:padding="5dp">
-
- <Button
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:onClick="onDiscoverResourceClick"
- android:text="@string/discover_resource"
- android:id="@+id/di"
- android:layout_alignParentTop="true"
- android:layout_alignParentStart="true" />
-
- <TextView
- android:id="@+id/log"
- android:layout_width="fill_parent"
- android:layout_height="250dp"
- android:ems="10"
- android:layout_weight="0.26"
- android:layout_alignParentStart="true"
- android:layout_alignParentBottom="true"
- android:background="#32437200"
- android:padding="10dp" />
-
- <ListView
- android:layout_width="wrap_content"
- android:layout_height="376dp"
- android:id="@+id/ResourceListView"
- android:layout_below="@+id/di"
- android:layout_alignParentStart="true"
- android:layout_above="@+id/log" />
-
-</RelativeLayout>
+++ /dev/null
-<?xml version="1.0" encoding="utf-8"?>
-<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent" android:layout_height="match_parent">
-
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="/softsensor/discomfortIndex/1"
- android:id="@+id/textView_uri"
- android:layout_alignBaseline="@+id/button_get"
- android:layout_alignBottom="@+id/button_get"
- android:layout_alignParentStart="true"
- android:paddingStart="10dp"
- android:textStyle="bold" />
-
- <Button
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Get"
- android:id="@+id/button_get"
- android:layout_alignParentTop="true"
- android:layout_toStartOf="@+id/button_observe" />
-
- <ToggleButton
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:id="@+id/button_observe"
- android:layout_alignBottom="@+id/button_get"
- android:layout_alignParentEnd="true"
- android:textOff="Observe"
- android:textOn="Observe" />
-
-</RelativeLayout>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="utf-8"?>
-<resources>
- <style name="AppTheme" parent="android:Theme.Material.Light">
- </style>
-</resources>
+++ /dev/null
-<resources>
- <string name="app_name">RCSampleClientApp</string>
- <string name="container_resource">Discover Container Resource</string>
- <string name="discover_resource">Discover Resource</string>
-</resources>
+++ /dev/null
-<resources>
-
- <!-- Base application theme. -->
- <style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
- <!-- Customize your theme here. -->
- </style>
-
-</resources>
+++ /dev/null
-// Top-level build file where you can add configuration options common to all sub-projects/modules.
-
-buildscript {
- repositories {
- jcenter()
- }
- dependencies {
- classpath 'com.android.tools.build:gradle:1.0.0'
-
- // NOTE: Do not place your application dependencies here; they belong
- // in the individual module build.gradle files
- }
-}
-
-allprojects {
- repositories {
- jcenter()
-
- flatDir {
- dirs 'libs'
- }
- }
-}
+++ /dev/null
-include ':app'
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<module external.linked.project.id="RCSampleServerApp" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$" external.system.id="GRADLE" external.system.module.group="" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
- <component name="FacetManager">
- <facet type="java-gradle" name="Java-Gradle">
- <configuration>
- <option name="BUILD_FOLDER_PATH" value="$MODULE_DIR$/build" />
- <option name="BUILDABLE" value="false" />
- </configuration>
- </facet>
- </component>
- <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_7" inherit-compiler-output="true">
- <exclude-output />
- <content url="file://$MODULE_DIR$">
- <excludeFolder url="file://$MODULE_DIR$/.gradle" />
- </content>
- <orderEntry type="jdk" jdkName="1.8" jdkType="JavaSDK" />
- <orderEntry type="sourceFolder" forTests="false" />
- </component>
-</module>
+++ /dev/null
-To build the app
-
-1. build Iotivity with TARGET_OS=android
-
-2. Copy aar files into app/libs folder
- - {Iotivity_root}/android/android_api/base/build/outputs/aar/iotivity-{TARGET_ARCH}-base-{MODE}.aar
- - {Iotivity_root}/service/resource-encapsulation/android/service/build/outputs/aar/iotivity-{TARGET_ARCH}-service-{MODE}.aar
-
-3. Configure dependencies for libs in app/build.gradle
- - default TARGET_ARCH is armeabi
- - default MODE is release
-
- for example, if you build Iotivity as follows,
-
- $scons TARGET_OS=android TARGET_ARCH=x86 RELEASE=0
-
- then, dependencies should be modified like below
-
- dependencies {
- compile(name:'iotivity-x86-service-debug', ext:'aar')
- compile(name:'iotivity-x86-base-debug', ext:'aar')
- }
-
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<module external.linked.project.id=":app" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$/.." external.system.id="GRADLE" external.system.module.group="RCSampleServerApp" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
- <component name="FacetManager">
- <facet type="android-gradle" name="Android-Gradle">
- <configuration>
- <option name="GRADLE_PROJECT_PATH" value=":app" />
- </configuration>
- </facet>
- <facet type="android" name="Android">
- <configuration>
- <option name="SELECTED_BUILD_VARIANT" value="debug" />
- <option name="SELECTED_TEST_ARTIFACT" value="_android_test_" />
- <option name="ASSEMBLE_TASK_NAME" value="assembleDebug" />
- <option name="COMPILE_JAVA_TASK_NAME" value="compileDebugSources" />
- <option name="ASSEMBLE_TEST_TASK_NAME" value="assembleDebugAndroidTest" />
- <option name="COMPILE_JAVA_TEST_TASK_NAME" value="compileDebugAndroidTestSources" />
- <afterSyncTasks>
- <task>generateDebugAndroidTestSources</task>
- <task>generateDebugSources</task>
- </afterSyncTasks>
- <option name="ALLOW_USER_CONFIGURATION" value="false" />
- <option name="MANIFEST_FILE_RELATIVE_PATH" value="/src/main/AndroidManifest.xml" />
- <option name="RES_FOLDER_RELATIVE_PATH" value="/src/main/res" />
- <option name="RES_FOLDERS_RELATIVE_PATH" value="file://$MODULE_DIR$/src/main/res" />
- <option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" />
- </configuration>
- </facet>
- </component>
- <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_7" inherit-compiler-output="false">
- <output url="file://$MODULE_DIR$/build/intermediates/classes/debug" />
- <output-test url="file://$MODULE_DIR$/build/intermediates/classes/androidTest/debug" />
- <exclude-output />
- <content url="file://$MODULE_DIR$">
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/debug" isTestSource="false" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/debug" isTestSource="false" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/debug" isTestSource="false" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/debug" isTestSource="false" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/debug" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/resValues/debug" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/androidTest/debug" isTestSource="true" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/androidTest/debug" isTestSource="true" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/androidTest/debug" isTestSource="true" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/androidTest/debug" isTestSource="true" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/androidTest/debug" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/resValues/androidTest/debug" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/res" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/resources" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/assets" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/aidl" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/java" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/jni" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/rs" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/res" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/assets" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/aidl" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/jni" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/rs" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/res" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/resources" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/assets" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/aidl" isTestSource="true" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/java" isTestSource="true" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/jni" isTestSource="true" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/rs" isTestSource="true" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/assets" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/bundles" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/classes" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/coverage-instrumented-classes" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dependency-cache" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex-cache" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/exploded-aar/iotivity-armeabi-v7a-resource-container-release/jars" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/exploded-aar/iotivity-base-armeabi-v7a-release/jars" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/jacoco" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/javaResources" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/libs" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/lint" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/manifests" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/ndk" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/pre-dexed" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/proguard" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/res" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/rs" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/symbols" />
- <excludeFolder url="file://$MODULE_DIR$/build/outputs" />
- <excludeFolder url="file://$MODULE_DIR$/build/tmp" />
- </content>
- <orderEntry type="jdk" jdkName="Android API 21 Platform" jdkType="Android SDK" />
- <orderEntry type="sourceFolder" forTests="false" />
- <orderEntry type="library" exported="" name="iotivity-armeabi-v7a-resource-container-release-" level="project" />
- <orderEntry type="library" exported="" name="iotivity-base-armeabi-v7a-release-" level="project" />
- </component>
-</module>
+++ /dev/null
-apply plugin: 'com.android.application'
-
-android {
- compileSdkVersion 21
- buildToolsVersion "20.0.0"
-
- defaultConfig {
- applicationId "org.iotivity.service.sample.resourcecontainer"
- minSdkVersion 21
- targetSdkVersion 21
- versionCode 1
- versionName "1.0"
- }
- buildTypes {
- release {
- minifyEnabled false
- proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
- }
- }
-
- /*packagingOptions{
- exclude 'lib/armeabi-v7a/librcs_client.so'
- exclude 'lib/armeabi-v7a/librcs_common.so'
- exclude 'lib/armeabi-v7a/librcs_server.so'
- }*/
-
-}
-
-dependencies {
- compile fileTree(include: ['*.jar'], dir: 'libs')
- //provided(name:'iotivity-armeabi-v7a-service-release', ext:'aar')
- compile(name:'iotivity-armeabi-v7a-resource-container-release', ext:'aar')
- // compile(name:'iotivity-armeabi-v7a-resource-container-debug', ext:'aar')
- compile(name:'iotivity-base-armeabi-v7a-release', ext:'aar')
-}
+++ /dev/null
-<container>
- <bundle>
- <id>oic.bundle.discomfortIndexSensor</id>
- <path>/data/local/tmp/org.iotivity.service.sample.resourcecontainer.test/files/libSoftSensorBundle.so</path>
- <activator>disensor</activator>
- <version>1.0.0</version>
- <resources>
- <resourceInfo>
- <name>DiscomfortIndexSensor1</name>
- <resourceType>oic.r.sensor</resourceType>
- <outputs>
- <output>
- <name>discomfortIndex</name>
- <type>int</type>
- </output>
- <output>
- <name>humidity</name>
- <type>double</type>
- </output>
- <output>
- <name>temperature</name>
- <type>double</type>
- </output>
- </outputs>
- <inputs>
- <input>
- <name>humidity</name>
- <type>double</type>
- <resourceType>oic.r.humidity</resourceType>
- </input>
- <input>
- <name>temperature</name>
- <type>double</type>
- <resourceType>oic.r.temperature</resourceType>
- </input>
- </inputs>
- </resourceInfo>
- </resources>
- </bundle>
- <!--
- <bundle>
- <id>oic.android.sample</id>
- <path>org.iotivity.service.sample.androidbundle.apk</path>
- <activator>org.iotivity.service.sample.androidbundle.SampleActivator</activator>
- <version>1.0.0</version>
- <resources>
- <resourceInfo>
- <name>LightResource1</name>
- <resourceType>oic.r.light</resourceType>
- <resourceUri>/android/light/1</resourceUri>
- </resourceInfo>
- <resourceInfo>
- <name>LightIntensity1</name>
- <resourceType>oic.r.lightintensity</resourceType>
- <resourceUri>/android/lightintensity/1</resourceUri>
- </resourceInfo>
- <resourceInfo>
- <name>Humidity1</name>
- <resogitkurceType>oic.r.humidity</resogitkurceType>
- <resourceUri>/android/humidity/1</resourceUri>
- </resourceInfo>
- <resourceInfo>
- <name>Tepmerature1</name>
- <resourceType>oic.r.temperature</resourceType>
- <resourceUri>/android/temperature/1</resourceUri>
- </resourceInfo>
- <resourceInfo>
- <name>Gyroscope1</name>
- <resourceType>oic.r.gyroscope</resourceType>
- <resourceUri>/android/gyroscope/1</resourceUri>
- </resourceInfo>
- <resourceInfo>
- <name>DiscomfortIndexSensor1</name>
- <resourceType>oic.r.discomfortindex</resourceType>
- <resourceUri>/android/discomfortindex/1</resourceUri>
- <outputs>
- <output>
- <name>discomfortIndex</name>
- <type>int</type>
- </output>
- <output>
- <name>humidity</name>
- <type>double</type>
- </output>
- <output>
- <name>temperature</name>
- <type>double</type>
- </output>
- </outputs>
- <inputs>
- <input>
- <name>humidity</name>
- <type>double</type>
- <resourceType>oic.r.humidity</resourceType>
- </input>
- <input>
- <name>temperature</name>
- <type>double</type>
- <resourceType>oic.r.temperature</resourceType>
- </input>
- </inputs>
- </resourceInfo>
- </resources>
- </bundle>-->
-</container>
\ No newline at end of file
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-package org.iotivity.service.sample.container;
-
-import android.test.InstrumentationTestCase;
-import android.util.Log;
-
-import org.iotivity.service.resourcecontainer.RcsResourceContainer;
-
-import java.util.HashMap;
-
-public class ResourceContainerTest extends InstrumentationTestCase {
- private RcsResourceContainer resourceContainerInstance;
- private final String sdCardDir =
- "/data/local/tmp/org.iotivity.service.sample.resourcecontainer.test/files/";
-
- @Override
- public void setUp(){
- resourceContainerInstance = new RcsResourceContainer(getInstrumentation().getContext());
- }
-
- public void testStartContainer() {
- resourceContainerInstance.startContainer("");
- assertTrue(resourceContainerInstance.listBundles().size() == 0);
- resourceContainerInstance.stopContainer();
- }
-
- public void testAddConfig(){
- resourceContainerInstance.startContainer("");
- //resourceContainerInstance.addBundle("");
- assertTrue(resourceContainerInstance.listBundles().size() == 0);
- resourceContainerInstance.stopContainer();
- }
-
- public void testStartBundle(){
- resourceContainerInstance.startBundle("not.existing");
- assertEquals(0, resourceContainerInstance.listBundles().size());
- }
-
- public void testStopBundle(){
- resourceContainerInstance.startBundle("not.existing");
- assertEquals(0, resourceContainerInstance.listBundles().size());
- }
-
- public void testAddBundle(){
- resourceContainerInstance.startContainer(
- "");
-
- resourceContainerInstance.addBundle("oic.bundle.test", "",
- sdCardDir + "libSoftSensorBundle.so",
- "disensor", new HashMap<String, String>());
- resourceContainerInstance.startBundle("oic.bundle.test");
- resourceContainerInstance.stopContainer();
- }
-}
\ No newline at end of file
+++ /dev/null
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="org.iotivity.service.sample.container">
-
- <uses-permission android:name="android.permission.INTERNET" />
- <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
-
- <uses-permission android:name="android.permission.CAMERA" />
- <uses-permission android:name="android.permission.FLASHLIGHT"/>
- <uses-permission android:name="android.permission.WAKE_LOCK"/>
- <uses-feature android:name="android.hardware.camera" />
- <uses-feature android:name="android.hardware.camera.autofocus" />
- <uses-feature android:name="android.hardware.camera.flash" />
-
- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE">
- </uses-permission>
- <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE">
- </uses-permission>
-
- <application android:allowBackup="true" android:label="@string/app_name"
- android:icon="@mipmap/ic_launcher" android:theme="@style/AppTheme">
-
- <activity
- android:name="org.iotivity.service.sample.container.ResourceContainerActivity"
- android:label="@string/app_name" >
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
-
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
- </application>
-
-</manifest>
+++ /dev/null
-<container>
-<!--
- <bundle>
- <id>oic.android.sample</id>
- <path>data/data/org.iotivity.service.sample.resourcecontainer/files/android_sample_bundle.jar</path>
- <activator>org.iotivity.service.sample.androidbundle.SampleActivator</activator>
- <version>1.0.0</version>
- <resources>
- <resourceInfo>
- <name>LightResource1</name>
- <resourceType>oic.r.light</resourceType>
- <resourceUri>/android/light/1</resourceUri>
- </resourceInfo>
- <resourceInfo>
- <name>LightIntensity1</name>
- <resourceType>oic.r.lightintensity</resourceType>
- <resourceUri>/android/lightintensity/1</resourceUri>
- </resourceInfo>
- <resourceInfo>
- <name>Humidity1</name>
- <resourceType>oic.r.humidity</resourceType>
- <resourceUri>/android/humidity/1</resourceUri>
- </resourceInfo>
- <resourceInfo>
- <name>Tepmerature1</name>
- <resourceType>oic.r.temperature</resourceType>
- <resourceUri>/android/temperature/1</resourceUri>
- </resourceInfo>
- <resourceInfo>
- <name>Gyroscope1</name>
- <resourceType>oic.r.gyroscope</resourceType>
- <resourceUri>/android/gyroscope/1</resourceUri>
- </resourceInfo>
- <resourceInfo>
- <name>DiscomfortIndexSensor1</name>
- <resourceType>oic.r.discomfortindex</resourceType>
- <resourceUri>/android/discomfortindex/1</resourceUri>
- <resourceClass>org.iotivity.service.sample.androidbundle.resources.DiscomfortIndexResource</resourceClass>
- <outputs>
- <output>
- <name>discomfortIndex</name>
- <type>int</type>
- </output>
- <output>
- <name>humidity</name>
- <type>double</type>
- </output>
- <output>
- <name>temperature</name>
- <type>double</type>
- </output>
- </outputs>
- <inputs>
- <input>
- <name>humidity</name>
- <type>double</type>
- <resourceType>oic.r.humidity</resourceType>
- </input>
- <input>
- <name>temperature</name>
- <type>double</type>
- <resourceType>oic.r.temperature</resourceType>
- </input>
- </inputs>
- </resourceInfo>
- </resources>
- </bundle>
- <bundle>
- <id>oic.bundle.discomfortIndexSensor</id>
- <path>data/data/org.iotivity.service.sample.resourcecontainer/files/libDISensorBundle.so</path>
- <activator>disensor</activator>
- <version>1.0.0</version>
- <resources>
- <resourceInfo>
- <name>DiscomfortIndexSensor1</name>
- <resourceType>oic.r.sensor</resourceType>
- <outputs>
- <output>
- <name>discomfortIndex</name>
- <type>int</type>
- </output>
- <output>
- <name>humidity</name>
- <type>double</type>
- </output>
- <output>
- <name>temperature</name>
- <type>double</type>
- </output>
- </outputs>
- <inputs>
- <input>
- <name>humidity</name>
- <type>double</type>
- <resourceType>oic.r.humidity</resourceType>
- </input>
- <input>
- <name>temperature</name>
- <type>double</type>
- <resourceType>oic.r.temperature</resourceType>
- </input>
- </inputs>
- </resourceInfo>
- </resources>
- </bundle>
--->
-</container>
\ No newline at end of file
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-package org.iotivity.service.sample.container;
-
-import android.content.Context;
-import android.os.Message;
-
-import android.os.PowerManager;
-import android.util.Log;
-
-import org.iotivity.service.resourcecontainer.RcsBundleInfo;
-import org.iotivity.service.resourcecontainer.RcsResourceContainer;
-
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-/**
- * For calling the Resource Container APIs as per user selection on UI and for
- * updating the UI
- *
- * It contains all the Resource Container APIs.
- */
-public class ResourceContainer {
-
- private RcsResourceContainer containerInstance;
- public static String logMessage;
-
- private static ResourceContainerActivity resourceContainerActivityInstance;
- private static Message msg;
- public static boolean startBundleFlag;
- private static boolean isStarted = false;
- PowerManager pm = null;
- PowerManager.WakeLock wl = null;
-
- // constructor
- public ResourceContainer() {
- resourceContainerActivityInstance = ResourceContainerActivity
- .getResourceContainerActivityObj();
- containerInstance = new RcsResourceContainer(
- resourceContainerActivityInstance.getApplicationContext());
- pm = (PowerManager) resourceContainerActivityInstance.getApplicationContext().
- getSystemService(Context.POWER_SERVICE);
- }
-
- // Start Container
- public void startContainer(String sdCardPath) {
-
- String configFile = sdCardPath + "/ResourceContainerConfig.xml";
- 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 ";
-
- ResourceContainerActivity.setMessageLog(logMessage);
- msg = Message.obtain();
- msg.what = 1;
- resourceContainerActivityInstance.getHandler().sendMessage(msg);
-
- msg = Message.obtain();
- msg.what = 0;
- resourceContainerActivityInstance.getHandler().sendMessage(msg);
-
- // initialize the information of the bundles
- // which registered at the starting time of the container
- List<RcsBundleInfo> bundleList = containerInstance.listBundles();
- Iterator<RcsBundleInfo> it = bundleList.iterator();
-
- while (it.hasNext())
- {
- String id = ((RcsBundleInfo) it.next()).getID();
- if (id.equals(ExampleBundleDescription.DIBundle.mBundleId)) {
- ExampleBundleDescription.DIBundle.isStarted = true;
- }
- else if (id.equals(ExampleBundleDescription.DIAndroidBundle.mBundleId)) {
- ExampleBundleDescription.DIAndroidBundle.isStarted = true;
- }
- }
- }
- }
-
- // Stop Container
- public void stopContainer() {
-
- if (isStarted) {
- containerInstance.stopContainer();
- logMessage = "Container stopped";
- isStarted = false;
- wl.release();
- } else {
- logMessage = "Container not started";
- }
-
- ResourceContainerActivity.setMessageLog(logMessage);
- msg = Message.obtain();
- msg.what = 1;
- resourceContainerActivityInstance.getHandler().sendMessage(msg);
- }
-
- // List Bundle Resources
- public void listBundleResources(String bundleId) {
-
- List<String> bundleResources = containerInstance
- .listBundleResources(bundleId);
- Iterator<String> it = bundleResources.iterator();
- logMessage = "";
-
- if (0 == bundleResources.size()) {
- logMessage = logMessage + "No resource found in the bundle" + "\n";
- } else {
- while (it.hasNext()) {
- String element = (String) it.next();
- logMessage = logMessage + element + "\n";
- }
- }
- ResourceContainerActivity.setMessageLog(logMessage);
- msg = Message.obtain();
- msg.what = 1;
- resourceContainerActivityInstance.getHandler().sendMessage(msg);
- }
-
- // List Bundles
- public void listBundles() {
-
- List<RcsBundleInfo> bundleList = containerInstance.listBundles();
- Iterator<RcsBundleInfo> it = bundleList.iterator();
- int i = 0;
- logMessage = "";
- logMessage = logMessage + "size of bundleList : " + bundleList.size()
- + "\n\n";
-
- while (it.hasNext()) {
- i++;
- RcsBundleInfo object = (RcsBundleInfo) it.next();
- logMessage += "Bundle : " + i + " -: \n";
- logMessage += "ID : " + object.getID() + "\n";
- logMessage += "Lib Path: " + object.getPath() + "\n";
- if (!(object.getVersion().equalsIgnoreCase("")))
- logMessage += "version : " + object.getVersion() + "\n\n";
- else
- logMessage += "\n";
- }
- ResourceContainerActivity.setMessageLog(logMessage);
- msg = Message.obtain();
- msg.what = 1;
- resourceContainerActivityInstance.getHandler().sendMessage(msg);
- }
-
- public boolean bundleExists(String bundleId)
- {
- List<RcsBundleInfo> bundleList = containerInstance.listBundles();
- Iterator<RcsBundleInfo> it = bundleList.iterator();
-
- while (it.hasNext())
- {
- if (it.next().getID().equals(bundleId))
- return true;
- }
-
- return false;
- }
-
- // add Bundles
- public void addBundle(BundleInformation bundle) {
- if (bundleExists(bundle.mBundleId))
- logMessage = "Bundle \'" + bundle.mBundleId + "\' already added" + "\n";
-
- else {
- containerInstance
- .addBundle(bundle.mBundleId, bundle.mBundleUri,
- bundle.mBundlePath, bundle.mActivator, bundle.mBundleParams);
-
- logMessage = "bundle to add : " + "\n";
- logMessage = logMessage + "ID : " + bundle.mBundleId + "\n";
- logMessage = logMessage + "Uri: " + bundle.mBundleUri + "\n";
- logMessage = logMessage
- + "Path : "
- + bundle.mBundlePath
- + "\n\n";
- logMessage = logMessage + "bundle added successfully" + "\n";
- }
-
- ResourceContainerActivity.setMessageLog(logMessage);
- msg = Message.obtain();
- msg.what = 1;
- resourceContainerActivityInstance.getHandler().sendMessage(msg);
- }
-
- // remove Bundles
- public void removeBundle(BundleInformation bundle) {
-
- if (!bundleExists(bundle.mBundleId))
- logMessage = "Bundle \'" + bundle.mBundleId + "\' not added" + "\n";
-
- else {
- containerInstance.removeBundle(bundle.mBundleId);
-
- bundle.isStarted = false;
- logMessage = "bundle to remove : " + "\n";
- logMessage = logMessage + "ID : " + bundle.mBundleId + "\n\n";
- logMessage = logMessage + " bundle removed successfully" + "\n";
- }
-
- ResourceContainerActivity.setMessageLog(logMessage);
- msg = Message.obtain();
- msg.what = 1;
- resourceContainerActivityInstance.getHandler().sendMessage(msg);
- }
-
- // start Bundles
- public void startBundle(BundleInformation bundle) {
-
- if (!bundleExists(bundle.mBundleId)) {
- logMessage = "Bundle \'" + bundle.mBundleId + "\' not added" + "\n";
- } else if (bundle.isStarted) {
- logMessage = "Bundle \'" + bundle.mBundleId + "\' already started" + "\n";
- } else {
- bundle.isStarted = true;
- containerInstance.startBundle(bundle.mBundleId);
-
- logMessage = " bundle to start" + "\n";
- logMessage += " ID : " + bundle.mBundleId + "\n\n";
- logMessage += " bundle started successfully" + "\n";
- }
-
- ResourceContainerActivity.setMessageLog(logMessage);
- msg = Message.obtain();
- msg.what = 1;
- resourceContainerActivityInstance.getHandler().sendMessage(msg);
- }
-
- // Stop Bundles
- public void stopBundle(BundleInformation bundle) {
-
- if (!bundleExists(bundle.mBundleId)) {
- logMessage = "Bundle \'" + bundle.mBundleId + "\' not added" + "\n";
- }
- else if (!bundle.isStarted) {
- logMessage = "Bundle \'" + bundle.mBundleId + "\' is not Started" + "\n";
- } else {
- containerInstance.stopBundle(bundle.mBundleId);
- bundle.isStarted = false;
- logMessage = " bundle to stop" + "\n";
- logMessage = logMessage + " ID : " + bundle.mBundleId + "\n\n";
- logMessage = logMessage + " bundle stopped successfully" + "\n";
- }
-
- ResourceContainerActivity.setMessageLog(logMessage);
- msg = Message.obtain();
- msg.what = 1;
- resourceContainerActivityInstance.getHandler().sendMessage(msg);
- }
-}
-
-class ExampleBundleDescription
-{
- static final BundleInformation BMIBundle =
- new BundleInformation ("oic.bundle.BMISensor", "",
- "/data/data/org.iotivity.service.sample.resourcecontainer/files/" +
- "libBMISensorBundle.so",
- "bmisensor", new HashMap<String, String>());
-
- static final BundleInformation DIBundle =
- new BundleInformation ("oic.bundle.discomfortIndexSensor", "",
- "/data/data/org.iotivity.service.sample.resourcecontainer/files/" +
- "libDISensorBundle.so",
- "disensor", new HashMap<String, String>());
-
- static final BundleInformation DIAndroidBundle =
- new BundleInformation ("oic.android.sample", "",
- "org.iotivity.service.sample.androidbundle.apk",
- "org.iotivity.service.sample.androidbundle.SampleActivator",
- new HashMap<String, String>());
-}
-
-class BundleInformation
-{
- String mBundleId;
- String mBundleUri;
- String mBundlePath;
- String mActivator;
- Map<String, String> mBundleParams;
-
- Boolean isStarted;
-
- public BundleInformation(String id, String uri, String path, String activator, Map<String, String> params)
- {
- mBundleId = id;
- mBundleUri = uri;
- mBundlePath = path;
- mActivator = activator;
- mBundleParams = params;
- isStarted = false;
- }
-}
\ No newline at end of file
+++ /dev/null
-/******************************************************************
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- * <p/>
- * <p/>
- * <p/>
- * 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
- * <p/>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p/>
- * 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.iotivity.service.sample.container;
-
-import android.app.Activity;
-import android.app.AlertDialog;
-import android.content.Context;
-import android.content.DialogInterface;
-import android.content.res.AssetManager;
-import android.graphics.Typeface;
-import android.net.ConnectivityManager;
-import android.os.Bundle;
-import android.os.Handler;
-import android.os.Message;
-import android.util.Log;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.View.OnClickListener;
-import android.view.ViewGroup;
-import android.widget.BaseExpandableListAdapter;
-import android.widget.Button;
-import android.widget.EditText;
-import android.widget.ExpandableListAdapter;
-import android.widget.ExpandableListView;
-import android.widget.TextView;
-import android.widget.Toast;
-
-import org.iotivity.base.ModeType;
-import org.iotivity.base.OcPlatform;
-import org.iotivity.base.PlatformConfig;
-import org.iotivity.base.QualityOfService;
-import org.iotivity.base.ServiceType;
-
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-
-/**
- * Activity for handling user's selection on UI for Resource container APIs. &
- * for updating UI.
- */
-public class ResourceContainerActivity extends Activity {
-
- private final String LOG_TAG = "[RCSampleServerApp] "
- + this.getClass()
- .getSimpleName();
- private static ResourceContainerActivity resourceContainerActivityInstance;
- private ResourceContainer resourceContainerInstance;
- private static String logMessage;
-
- private Context context;
- public ExpandableListAdapter listAdapter;
- public ExpandableListView expListView;
- private int lastExpandedPosition = -1;
-
- public List<String> sensors;
- public List<String> diApiList;
- public List<String> bmiApiList;
- public List<String> diAndroidApiList;
- HashMap<String, List<String>> listChild;
-
- private static Handler mHandler;
- private Button startContainer;
- private Button listBundles;
- private static EditText logs;
- private static String sdCardPath;
-
- public static void setMessageLog(String message) {
- logMessage = message;
- }
-
- public static ResourceContainerActivity getResourceContainerActivityObj() {
- return resourceContainerActivityInstance;
- }
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
-
- super.onCreate(savedInstanceState);
- context = this;
-
- /*if (!isWifiConnected()) {
- showWifiUnavailableDialog();
- return;
- }*/
-
- configurePlatform();
- CopyAssetsToSDCard();
-
- setContentView(R.layout.resource_container);
- resourceContainerActivityInstance = this;
-
- resourceContainerInstance = new ResourceContainer();
-
- expListView = (ExpandableListView) findViewById(R.id.lvExp);
- startContainer = (Button) findViewById(R.id.startContainer);
- listBundles = (Button) findViewById(R.id.listBundles);
- listBundles.setEnabled(false);
- logs = (EditText) findViewById(R.id.log);
-
- sensors = new ArrayList<String>();
- bmiApiList = new ArrayList<String>();
- diApiList = new ArrayList<String>();
- diAndroidApiList = new ArrayList<String>();
- listChild = new HashMap<String, List<String>>();
-
- // Adding list items (header)
- sensors.add("BMI Sensor");
- sensors.add("Discomfort Index Sensor");
- sensors.add("Android Discomfort Index Sensor");
-
- // Adding child data [BMI sensor]
- bmiApiList.add("1. Add BMI sensor bundle");
- bmiApiList.add("2. Start BMI sensor bundle");
- bmiApiList.add("3. List bundle resources");
- bmiApiList.add("4. Stop BMI sensor bundle");
- bmiApiList.add("5. Remove BMI sensor bundle");
-
- // Adding child data [discomfort Index sensor]
- diApiList.add("1. Add DI sensor bundle");
- diApiList.add("2. Start DI sensor bundle");
- diApiList.add("3. List bundle resources");
- diApiList.add("4. Stop DI sensor bundle");
- diApiList.add("5. Remove DI sensor bundle");
-
- // Adding child data [discomfort Index sensor - android]
- diAndroidApiList.add("1. Add Android DI sensor bundle");
- diAndroidApiList.add("2. Start Android DI sensor bundle");
- diAndroidApiList.add("3. List bundle resources");
- diAndroidApiList.add("4. Stop Android DI sensor bundle");
- diAndroidApiList.add("5. Remove Android DI sensor bundle");
-
- listChild.put(sensors.get(0), bmiApiList);
- listChild.put(sensors.get(1), diApiList);
- listChild.put(sensors.get(2), diAndroidApiList);
- listAdapter = new ExpandableList(this, sensors, listChild);
-
- // getting the sd card path
- sdCardPath = this.getFilesDir().getPath();
-
- // handler for updating the UI i.e. MessageLog (TextBox) & ListView
- mHandler = new Handler() {
- @Override
- public void handleMessage(Message msg) {
- switch (msg.what) {
- case 0:
- expListView.setAdapter(listAdapter);
- expListView.bringToFront();
- break;
- case 1:
- logs.setText("");
- logs.setText(logMessage);
- Log.i(LOG_TAG, logMessage);
- break;
- case 2:
- listAdapter = null;
- expListView.setAdapter(listAdapter);
- break;
- }
- }
- };
- setHandler(mHandler);
-
- // StartContainer/stopContainer Button Listener
- startContainer.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
-
- String text = (String) startContainer.getText();
- if (text.contains("Start")) {
- resourceContainerInstance.startContainer(sdCardPath);
- listAdapter = new ExpandableList(ResourceContainerActivity
- .getResourceContainerActivityObj(), sensors,
- listChild);
- listBundles.setEnabled(true);
- startContainer.setText("Stop Container");
- } else {
- resourceContainerInstance.stopContainer();
- startContainer.setText("Start Container");
- listBundles.setEnabled(false);
- Message msg;
- msg = Message.obtain();
- msg.what = 2;
- resourceContainerActivityInstance.getHandler().sendMessage(
- msg);
- }
- }
- });
-
- // List Bundles Button Listener
- listBundles.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- resourceContainerInstance.listBundles();
- }
- });
-
-
- expListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
- @Override
- public void onGroupExpand(int groupPosition) {
- if (lastExpandedPosition != -1
- && groupPosition != lastExpandedPosition) {
- expListView.collapseGroup(lastExpandedPosition);
- }
- lastExpandedPosition = groupPosition;
- }
- });
-
- expListView
- .setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
-
- @Override
- public boolean onChildClick(ExpandableListView parent,
- View v, int groupPosition, int childPosition,
- long id) {
- BundleInformation bundleToTest;
-
- switch (groupPosition) {
- case 0:
- bundleToTest = ExampleBundleDescription.BMIBundle;
- break;
-
- case 1:
- bundleToTest = ExampleBundleDescription.DIBundle;
- break;
-
- case 2:
- bundleToTest = ExampleBundleDescription.DIAndroidBundle;
- break;
-
- default:
- return false;
- }
-
- switch (childPosition) {
- case 0:
- resourceContainerInstance.addBundle(bundleToTest);
- break;
-
- case 1:
- resourceContainerInstance.startBundle(bundleToTest);
- break;
-
- case 2:
- resourceContainerInstance
- .listBundleResources(bundleToTest.mBundleId);
- break;
-
- case 3:
- resourceContainerInstance.stopBundle(bundleToTest);
- break;
-
- case 4:
- resourceContainerInstance.removeBundle(bundleToTest);
- break;
-
- default:
- return false;
- }
- return true;
- }
- });
- }
-
- private void CopyAssetsToSDCard() {
- AssetManager assetManager = getAssets();
- String[] files = null;
- try {
- files = assetManager.list("lib");
- } catch (IOException e) {
- Log.e(LOG_TAG, e.getMessage());
- }
-
- for (String filename : files) {
- InputStream in = null;
- OutputStream out = null;
- try {
- in = assetManager.open("lib/" + filename);
- out = new FileOutputStream(context.getFilesDir().getParent()
- + "/files/" + filename);
- copyIndividualFile(in, out);
- in.close();
- in = null;
- out.flush();
- out.close();
- out = null;
- } catch (Exception e) {
- Log.e(LOG_TAG, e.getMessage());
- }
- }
- }
-
- private void copyIndividualFile(InputStream in, OutputStream out)
- throws IOException {
-
- Log.i(LOG_TAG, "copyIndividualFile");
- byte[] buffer = new byte[2048];
- int read;
- while ((read = in.read(buffer)) != -1) {
- out.write(buffer, 0, read);
- }
- }
-
- @Override
- public void onBackPressed() {
- listAdapter = null;
- expListView.setAdapter(listAdapter);
- resourceContainerInstance.stopContainer();
- ResourceContainer.startBundleFlag = false;
- super.onBackPressed();
- }
-
- // class for handling expandable list items
- public class ExpandableList extends BaseExpandableListAdapter {
-
- private Context mContext;
- private HashMap<String, List<String>> mListDataChild;
- private List<String> mListDataHeader;
-
- // constructor
- public ExpandableList(Context context, List<String> dataHeader,
- HashMap<String, List<String>> childData) {
- this.mContext = context;
- this.mListDataHeader = dataHeader;
- this.mListDataChild = childData;
- }
-
- // get the child ID
- @Override
- public long getChildId(int grpPosition, int childPosition) {
- return childPosition;
- }
-
- // get the child
- @Override
- public Object getChild(int grpPosition, int childPosititon) {
- return this.mListDataChild.get(
- this.mListDataHeader.get(grpPosition)).get(childPosititon);
- }
-
- // get Group View
- @Override
- public View getGroupView(int grpPosition, boolean isExpandable,
- View changeView, ViewGroup head) {
- String mainHeading = (String) getGroup(grpPosition);
- if (changeView == null) {
- LayoutInflater flater;
- flater = (LayoutInflater) this.mContext
- .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
- changeView = flater.inflate(R.layout.group, null);
- }
-
- TextView listHeader = (TextView) changeView
- .findViewById(R.id.ListHead);
- listHeader.setTypeface(null, Typeface.BOLD);
- listHeader.setText(mainHeading);
- return changeView;
- }
-
- // get Children count
- @Override
- public int getChildrenCount(int grpPosition) {
- int count = this.mListDataChild.get(
- this.mListDataHeader.get(grpPosition)).size();
- return count;
- }
-
- // Get Group
- @Override
- public Object getGroup(int grpPosition) {
- return this.mListDataHeader.get(grpPosition);
- }
-
- // get Group size
- @Override
- public int getGroupCount() {
- int size = this.mListDataHeader.size();
- return size;
- }
-
- // get Group ID
- @Override
- public long getGroupId(int grpPosition) {
- return grpPosition;
- }
-
- // get Group View
- @Override
- public View getChildView(int grpPosition, final int childPosition,
- boolean isLastItem, View changeView, ViewGroup head) {
-
- final String innerText = (String) getChild(grpPosition,
- childPosition);
-
- if (changeView == null) {
- LayoutInflater flater = (LayoutInflater) this.mContext
- .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
- changeView = flater.inflate(R.layout.list_item, null);
- }
-
- TextView textListChild = (TextView) changeView
- .findViewById(R.id.listItem);
-
- textListChild.setText(innerText);
- return changeView;
- }
-
- // To check whether child is selectable or not
- @Override
- public boolean isChildSelectable(int grpPosition, int childPosition) {
- return true;
- }
-
- // To check the stable IDs
- @Override
- public boolean hasStableIds() {
- return false;
- }
- }
-
- private void showWifiUnavailableDialog() {
- new AlertDialog.Builder(this)
- .setTitle("Error")
- .setMessage(
- "WiFi is not enabled/connected! Please connect the WiFi and start application again...")
- .setCancelable(false)
- .setPositiveButton("OK", new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- finish();
- }
- }).create().show();
- }
-
- private boolean isWifiConnected() {
- ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
- return connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
- .isConnected();
- }
-
- private void configurePlatform() {
- OcPlatform.Configure(new PlatformConfig(getApplicationContext(),
- ServiceType.IN_PROC, ModeType.CLIENT_SERVER, "0.0.0.0", 0,
- QualityOfService.LOW));
- Log.i(LOG_TAG, "Configuration done successfully");
- }
-
- public Handler getHandler() {
- return mHandler;
- }
-
- public void setHandler(Handler mHandler) {
- ResourceContainerActivity.mHandler = mHandler;
- }
-
- public void displayToastMessage(String message) {
- Toast toast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
- toast.show();
- Log.i(LOG_TAG, message);
- }
-}
+++ /dev/null
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:orientation="vertical"
- android:padding="8dp" >
-
- <TextView
- android:id="@+id/ListHead"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:paddingLeft="?android:attr/expandableListPreferredItemPaddingLeft"
- android:textSize="20dp" />
-
-</LinearLayout>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="55dip"
- android:orientation="vertical" >
-
- <TextView
- android:id="@+id/listItem"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:paddingBottom="5dp"
- android:paddingLeft="?android:attr/expandableListPreferredChildPaddingLeft"
- android:paddingTop="5dp"
- android:textSize="20dip" />
-
-</LinearLayout>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="utf-8"?>
-<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:padding="5dp">
-
- <Button
- android:id="@+id/startContainer"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentLeft="true"
- android:layout_alignParentTop="true"
- android:text="Start Container" />
-
- <ExpandableListView
- android:id="@+id/lvExp"
- android:layout_width="match_parent"
- android:layout_height="300dp"
- android:layout_below="@id/startContainer" />
-
- <Button
- android:id="@+id/listBundles"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentRight="true"
- android:layout_alignParentTop="true"
- android:text="List Bundles" />
-
- <EditText
- android:id="@+id/log"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:layout_alignParentBottom="true"
- android:layout_alignParentLeft="true"
- android:layout_below="@id/lvExp"
- android:editable="false"
- android:ems="10"
- android:background="#32437200"
- android:padding="10dp" />
-
-</RelativeLayout>
+++ /dev/null
-<?xml version="1.0" encoding="utf-8"?>
-<resources>
- <style name="AppTheme" parent="android:Theme.Material.Light">
- </style>
-</resources>
+++ /dev/null
-<resources>
- <string name="app_name">RCSampleServerApp</string>
- <string name="resource_container">Resource Container</string>
-</resources>
+++ /dev/null
-<resources>
- <style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
- </style>
-</resources>
+++ /dev/null
-// Top-level build file where you can add configuration options common to all sub-projects/modules.
-
-buildscript {
- repositories {
- maven{
- url "http://jcenter.bintray.com/"
- }
- }
- dependencies {
- classpath 'com.android.tools.build:gradle:1.3.0'
-
- // NOTE: Do not place your application dependencies here; they belong
- // in the individual module build.gradle files
- }
-}
-
-allprojects {
- repositories {
- maven{
- url "http://jcenter.bintray.com/"
- }
-
- flatDir {
- dirs 'libs'
- }
- }
-}
-
-
+++ /dev/null
-#!/usr/bin/env bash
-
-##############################################################################
-##
-## Gradle start up script for UN*X
-##
-##############################################################################
-
-# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
-DEFAULT_JVM_OPTS=""
-
-APP_NAME="Gradle"
-APP_BASE_NAME=`basename "$0"`
-
-# Use the maximum available, or set MAX_FD != -1 to use that value.
-MAX_FD="maximum"
-
-warn ( ) {
- echo "$*"
-}
-
-die ( ) {
- echo
- echo "$*"
- echo
- exit 1
-}
-
-# OS specific support (must be 'true' or 'false').
-cygwin=false
-msys=false
-darwin=false
-case "`uname`" in
- CYGWIN* )
- cygwin=true
- ;;
- Darwin* )
- darwin=true
- ;;
- MINGW* )
- msys=true
- ;;
-esac
-
-# For Cygwin, ensure paths are in UNIX format before anything is touched.
-if $cygwin ; then
- [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
-fi
-
-# Attempt to set APP_HOME
-# Resolve links: $0 may be a link
-PRG="$0"
-# Need this for relative symlinks.
-while [ -h "$PRG" ] ; do
- ls=`ls -ld "$PRG"`
- link=`expr "$ls" : '.*-> \(.*\)$'`
- if expr "$link" : '/.*' > /dev/null; then
- PRG="$link"
- else
- PRG=`dirname "$PRG"`"/$link"
- fi
-done
-SAVED="`pwd`"
-cd "`dirname \"$PRG\"`/" >&-
-APP_HOME="`pwd -P`"
-cd "$SAVED" >&-
-
-CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
-
-# Determine the Java command to use to start the JVM.
-if [ -n "$JAVA_HOME" ] ; then
- if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
- # IBM's JDK on AIX uses strange locations for the executables
- JAVACMD="$JAVA_HOME/jre/sh/java"
- else
- JAVACMD="$JAVA_HOME/bin/java"
- fi
- if [ ! -x "$JAVACMD" ] ; then
- die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
-
-Please set the JAVA_HOME variable in your environment to match the
-location of your Java installation."
- fi
-else
- JAVACMD="java"
- which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
-
-Please set the JAVA_HOME variable in your environment to match the
-location of your Java installation."
-fi
-
-# Increase the maximum file descriptors if we can.
-if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
- MAX_FD_LIMIT=`ulimit -H -n`
- if [ $? -eq 0 ] ; then
- if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
- MAX_FD="$MAX_FD_LIMIT"
- fi
- ulimit -n $MAX_FD
- if [ $? -ne 0 ] ; then
- warn "Could not set maximum file descriptor limit: $MAX_FD"
- fi
- else
- warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
- fi
-fi
-
-# For Darwin, add options to specify how the application appears in the dock
-if $darwin; then
- GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
-fi
-
-# For Cygwin, switch paths to Windows format before running java
-if $cygwin ; then
- APP_HOME=`cygpath --path --mixed "$APP_HOME"`
- CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
-
- # We build the pattern for arguments to be converted via cygpath
- ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
- SEP=""
- for dir in $ROOTDIRSRAW ; do
- ROOTDIRS="$ROOTDIRS$SEP$dir"
- SEP="|"
- done
- OURCYGPATTERN="(^($ROOTDIRS))"
- # Add a user-defined pattern to the cygpath arguments
- if [ "$GRADLE_CYGPATTERN" != "" ] ; then
- OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
- fi
- # Now convert the arguments - kludge to limit ourselves to /bin/sh
- i=0
- for arg in "$@" ; do
- CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
- CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
-
- if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
- eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
- else
- eval `echo args$i`="\"$arg\""
- fi
- i=$((i+1))
- done
- case $i in
- (0) set -- ;;
- (1) set -- "$args0" ;;
- (2) set -- "$args0" "$args1" ;;
- (3) set -- "$args0" "$args1" "$args2" ;;
- (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
- (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
- (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
- (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
- (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
- (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
- esac
-fi
-
-# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
-function splitJvmOpts() {
- JVM_OPTS=("$@")
-}
-eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
-JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
-
-exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
+++ /dev/null
-@if "%DEBUG%" == "" @echo off
-@rem ##########################################################################
-@rem
-@rem Gradle startup script for Windows
-@rem
-@rem ##########################################################################
-
-@rem Set local scope for the variables with windows NT shell
-if "%OS%"=="Windows_NT" setlocal
-
-@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
-set DEFAULT_JVM_OPTS=
-
-set DIRNAME=%~dp0
-if "%DIRNAME%" == "" set DIRNAME=.
-set APP_BASE_NAME=%~n0
-set APP_HOME=%DIRNAME%
-
-@rem Find java.exe
-if defined JAVA_HOME goto findJavaFromJavaHome
-
-set JAVA_EXE=java.exe
-%JAVA_EXE% -version >NUL 2>&1
-if "%ERRORLEVEL%" == "0" goto init
-
-echo.
-echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
-echo.
-echo Please set the JAVA_HOME variable in your environment to match the
-echo location of your Java installation.
-
-goto fail
-
-:findJavaFromJavaHome
-set JAVA_HOME=%JAVA_HOME:"=%
-set JAVA_EXE=%JAVA_HOME%/bin/java.exe
-
-if exist "%JAVA_EXE%" goto init
-
-echo.
-echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
-echo.
-echo Please set the JAVA_HOME variable in your environment to match the
-echo location of your Java installation.
-
-goto fail
-
-:init
-@rem Get command-line arguments, handling Windowz variants
-
-if not "%OS%" == "Windows_NT" goto win9xME_args
-if "%@eval[2+2]" == "4" goto 4NT_args
-
-:win9xME_args
-@rem Slurp the command line arguments.
-set CMD_LINE_ARGS=
-set _SKIP=2
-
-:win9xME_args_slurp
-if "x%~1" == "x" goto execute
-
-set CMD_LINE_ARGS=%*
-goto execute
-
-:4NT_args
-@rem Get arguments from the 4NT Shell from JP Software
-set CMD_LINE_ARGS=%$
-
-:execute
-@rem Setup the command line
-
-set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
-
-@rem Execute Gradle
-"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
-
-:end
-@rem End local scope for the variables with windows NT shell
-if "%ERRORLEVEL%"=="0" goto mainEnd
-
-:fail
-rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
-rem the _cmd.exe /c_ return code!
-if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
-exit /b 1
-
-:mainEnd
-if "%OS%"=="Windows_NT" endlocal
-
-:omega
+++ /dev/null
-include ':app'
+++ /dev/null
-.gradle
-/local.properties
-/.idea/workspace.xml
-/.idea/libraries
-.DS_Store
-/build/*
-/service/build/*
-/service/src/main/obj/*
-/service/src/main/libs/*
+++ /dev/null
-import os
-import platform
-Import('env')
-
-android_home = env.get('ANDROID_HOME')
-
-ANDROID_TARGET_ARCH = env.get('TARGET_ARCH')
-if env.get('RELEASE'):
- ANDROID_RELEASE="release"
-else:
- ANDROID_RELEASE="debug"
-
-os.environ['ANDROID_HOME'] = env.get('ANDROID_HOME')
-os.environ['ANDROID_NDK_HOME'] = env.get('ANDROID_NDK')
-
-if not os.path.exists(android_home + '/platforms/android-21') or not os.path.exists(android_home + '/build-tools/20.0.0'):
- print '''
-***************************************** Info ********************************
-* Either 'Android API 21' is not installed or 'Android SDK Build Tools *
-* 20.0.0' is not installed. The Android SDK Manager will now open. Please *
-* be sure to deselect all options, then select the following 2 packages: *
-* 1. Under "Tools" select "Android SDK Build-tools" Revision 20. *
-* 2. Under "Android 5.0.1 (API 21)" select "SDK Platform" *
-* 3. Continue by selecting "Install 2 Packages" *
-* *
-* NOTE: If you have an http proxy, please press ctrl+c now and edit/create *
-* the following file in your $HOME directory as follows: *
-* *
-* Edit/Create file: "$HOME/.android/androidtool.cfg" *
-* *
-* http.proxyPort=<YOUR_PORT_NUMBER> *
-* sdkman.monitor.density=108 *
-* http.proxyHost=<YOUR_HTTP_PROXY_ADDRESS> *
-* sdkman.show.update.only=true *
-* sdkman.ask.adb.restart=false *
-* sdkman.force.http=true *
-* sdkman.show.updateonly=true *
-* *
-*******************************************************************************
-
-...Opening Android SDK Manager now. Once you are finished, the build will continue.
-'''
- os.system(android_home + '/tools/android')
-
-
-def ensure_libs(target, source, env):
- return target, [source, env.get('BUILD_DIR') + 'librcs_server.so',
- env.get('BUILD_DIR') + 'librcs_client.so']
-
-jdk_env = Environment(ENV=os.environ)
-jdk_env['BUILDERS']['Gradle'] = Builder(action = env.get('ANDROID_GRADLE') +
- ' build -bservice/resource-encapsulation/android/build.gradle -PTARGET_ARCH=%s -PRELEASE=%s --stacktrace' %(ANDROID_TARGET_ARCH, ANDROID_RELEASE),
- emitter = ensure_libs)
-jdk_env['BUILD_DIR'] = env.get('BUILD_DIR')
-jdk_env.Gradle(target="service/objs",
- source="service/src/main/java/org/iotivity/service/RcsResourceAttributes.java")
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<module external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$" external.system.id="GRADLE" external.system.module.group="" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
- <component name="FacetManager">
- <facet type="java-gradle" name="Java-Gradle">
- <configuration>
- <option name="BUILD_FOLDER_PATH" value="$MODULE_DIR$/build" />
- </configuration>
- </facet>
- </component>
- <component name="NewModuleRootManager" inherit-compiler-output="true">
- <exclude-output />
- <content url="file://$MODULE_DIR$">
- <excludeFolder url="file://$MODULE_DIR$/.gradle" />
- </content>
- <orderEntry type="inheritedJdk" />
- <orderEntry type="sourceFolder" forTests="false" />
- </component>
-</module>
-
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-// Top-level build file where you can add configuration options common to all sub-projects/modules.
-
-buildscript {
- repositories {
- jcenter()
- }
- dependencies {
- classpath 'com.android.tools.build:gradle:1.3.0'
-
- // NOTE: Do not place your application dependencies here; they belong
- // in the individual module build.gradle files
- }
-}
-
-allprojects {
- repositories {
- jcenter {
- url "http://jcenter.bintray.com/"
- }
- }
-}
+++ /dev/null
-#
-# //******************************************************************
-# //
-# // Copyright 2015 Intel Corporation.
-# //
-# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-# //
-# // 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.
-# //
-# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#
-
-# Project-wide Gradle settings.
-
-# IDE (e.g. Android Studio) users:
-# Gradle settings configured through the IDE *will override*
-# any settings specified in this file.
-
-# For more details on how to configure your build environment visit
-# http://www.gradle.org/docs/current/userguide/build_environment.html
-
-# Specifies the JVM arguments used for the daemon process.
-# The setting is particularly useful for tweaking memory settings.
-# Default value: -Xmx10248m -XX:MaxPermSize=256m
-# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
-
-# When configured, Gradle will run in incubating parallel mode.
-# This option should only be used with decoupled projects. More details, visit
-# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
-# org.gradle.parallel=true
+++ /dev/null
-#!/usr/bin/env bash
-
-##############################################################################
-##
-## Gradle start up script for UN*X
-##
-##############################################################################
-
-# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
-DEFAULT_JVM_OPTS=""
-
-APP_NAME="Gradle"
-APP_BASE_NAME=`basename "$0"`
-
-# Use the maximum available, or set MAX_FD != -1 to use that value.
-MAX_FD="maximum"
-
-warn ( ) {
- echo "$*"
-}
-
-die ( ) {
- echo
- echo "$*"
- echo
- exit 1
-}
-
-# OS specific support (must be 'true' or 'false').
-cygwin=false
-msys=false
-darwin=false
-case "`uname`" in
- CYGWIN* )
- cygwin=true
- ;;
- Darwin* )
- darwin=true
- ;;
- MINGW* )
- msys=true
- ;;
-esac
-
-# For Cygwin, ensure paths are in UNIX format before anything is touched.
-if $cygwin ; then
- [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
-fi
-
-# Attempt to set APP_HOME
-# Resolve links: $0 may be a link
-PRG="$0"
-# Need this for relative symlinks.
-while [ -h "$PRG" ] ; do
- ls=`ls -ld "$PRG"`
- link=`expr "$ls" : '.*-> \(.*\)$'`
- if expr "$link" : '/.*' > /dev/null; then
- PRG="$link"
- else
- PRG=`dirname "$PRG"`"/$link"
- fi
-done
-SAVED="`pwd`"
-cd "`dirname \"$PRG\"`/" >&-
-APP_HOME="`pwd -P`"
-cd "$SAVED" >&-
-
-CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
-
-# Determine the Java command to use to start the JVM.
-if [ -n "$JAVA_HOME" ] ; then
- if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
- # IBM's JDK on AIX uses strange locations for the executables
- JAVACMD="$JAVA_HOME/jre/sh/java"
- else
- JAVACMD="$JAVA_HOME/bin/java"
- fi
- if [ ! -x "$JAVACMD" ] ; then
- die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
-
-Please set the JAVA_HOME variable in your environment to match the
-location of your Java installation."
- fi
-else
- JAVACMD="java"
- which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
-
-Please set the JAVA_HOME variable in your environment to match the
-location of your Java installation."
-fi
-
-# Increase the maximum file descriptors if we can.
-if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
- MAX_FD_LIMIT=`ulimit -H -n`
- if [ $? -eq 0 ] ; then
- if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
- MAX_FD="$MAX_FD_LIMIT"
- fi
- ulimit -n $MAX_FD
- if [ $? -ne 0 ] ; then
- warn "Could not set maximum file descriptor limit: $MAX_FD"
- fi
- else
- warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
- fi
-fi
-
-# For Darwin, add options to specify how the application appears in the dock
-if $darwin; then
- GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
-fi
-
-# For Cygwin, switch paths to Windows format before running java
-if $cygwin ; then
- APP_HOME=`cygpath --path --mixed "$APP_HOME"`
- CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
-
- # We build the pattern for arguments to be converted via cygpath
- ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
- SEP=""
- for dir in $ROOTDIRSRAW ; do
- ROOTDIRS="$ROOTDIRS$SEP$dir"
- SEP="|"
- done
- OURCYGPATTERN="(^($ROOTDIRS))"
- # Add a user-defined pattern to the cygpath arguments
- if [ "$GRADLE_CYGPATTERN" != "" ] ; then
- OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
- fi
- # Now convert the arguments - kludge to limit ourselves to /bin/sh
- i=0
- for arg in "$@" ; do
- CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
- CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
-
- if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
- eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
- else
- eval `echo args$i`="\"$arg\""
- fi
- i=$((i+1))
- done
- case $i in
- (0) set -- ;;
- (1) set -- "$args0" ;;
- (2) set -- "$args0" "$args1" ;;
- (3) set -- "$args0" "$args1" "$args2" ;;
- (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
- (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
- (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
- (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
- (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
- (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
- esac
-fi
-
-# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
-function splitJvmOpts() {
- JVM_OPTS=("$@")
-}
-eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
-JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
-
-exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
+++ /dev/null
-@if "%DEBUG%" == "" @echo off
-@rem ##########################################################################
-@rem
-@rem Gradle startup script for Windows
-@rem
-@rem ##########################################################################
-
-@rem Set local scope for the variables with windows NT shell
-if "%OS%"=="Windows_NT" setlocal
-
-@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
-set DEFAULT_JVM_OPTS=
-
-set DIRNAME=%~dp0
-if "%DIRNAME%" == "" set DIRNAME=.
-set APP_BASE_NAME=%~n0
-set APP_HOME=%DIRNAME%
-
-@rem Find java.exe
-if defined JAVA_HOME goto findJavaFromJavaHome
-
-set JAVA_EXE=java.exe
-%JAVA_EXE% -version >NUL 2>&1
-if "%ERRORLEVEL%" == "0" goto init
-
-echo.
-echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
-echo.
-echo Please set the JAVA_HOME variable in your environment to match the
-echo location of your Java installation.
-
-goto fail
-
-:findJavaFromJavaHome
-set JAVA_HOME=%JAVA_HOME:"=%
-set JAVA_EXE=%JAVA_HOME%/bin/java.exe
-
-if exist "%JAVA_EXE%" goto init
-
-echo.
-echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
-echo.
-echo Please set the JAVA_HOME variable in your environment to match the
-echo location of your Java installation.
-
-goto fail
-
-:init
-@rem Get command-line arguments, handling Windowz variants
-
-if not "%OS%" == "Windows_NT" goto win9xME_args
-if "%@eval[2+2]" == "4" goto 4NT_args
-
-:win9xME_args
-@rem Slurp the command line arguments.
-set CMD_LINE_ARGS=
-set _SKIP=2
-
-:win9xME_args_slurp
-if "x%~1" == "x" goto execute
-
-set CMD_LINE_ARGS=%*
-goto execute
-
-:4NT_args
-@rem Get arguments from the 4NT Shell from JP Software
-set CMD_LINE_ARGS=%$
-
-:execute
-@rem Setup the command line
-
-set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
-
-@rem Execute Gradle
-"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
-
-:end
-@rem End local scope for the variables with windows NT shell
-if "%ERRORLEVEL%"=="0" goto mainEnd
-
-:fail
-rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
-rem the _cmd.exe /c_ return code!
-if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
-exit /b 1
-
-:mainEnd
-if "%OS%"=="Windows_NT" endlocal
-
-:omega
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<module external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$/.." external.system.id="GRADLE" external.system.module.group="android_api" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
- <component name="FacetManager">
- <facet type="android-gradle" name="Android-Gradle">
- <configuration>
- <option name="GRADLE_PROJECT_PATH" value=":base" />
- </configuration>
- </facet>
- <facet type="android" name="Android">
- <configuration>
- <option name="SELECTED_BUILD_VARIANT" value="debug" />
- <option name="ASSEMBLE_TASK_NAME" value="assembleDebug" />
- <option name="COMPILE_JAVA_TASK_NAME" value="compileDebugSources" />
- <option name="ASSEMBLE_TEST_TASK_NAME" value="assembleDebugTest" />
- <option name="SOURCE_GEN_TASK_NAME" value="generateDebugSources" />
- <option name="TEST_SOURCE_GEN_TASK_NAME" value="generateDebugTestSources" />
- <option name="ALLOW_USER_CONFIGURATION" value="false" />
- <option name="MANIFEST_FILE_RELATIVE_PATH" value="/src/main/AndroidManifest.xml" />
- <option name="RES_FOLDER_RELATIVE_PATH" value="/src/main/res" />
- <option name="RES_FOLDERS_RELATIVE_PATH" value="" />
- <option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" />
- <option name="LIBRARY_PROJECT" value="true" />
- </configuration>
- </facet>
- </component>
- <component name="NewModuleRootManager" inherit-compiler-output="false">
- <output url="file://$MODULE_DIR$/build/intermediates/classes/debug" />
- <output-test url="file://$MODULE_DIR$/build/intermediates/classes/test/debug" />
- <exclude-output />
- <content url="file://$MODULE_DIR$">
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/debug" isTestSource="false" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/debug" isTestSource="false" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/debug" isTestSource="false" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/debug" isTestSource="false" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/debug" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/debug" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/test/debug" isTestSource="true" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/test/debug" isTestSource="true" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/test/debug" isTestSource="true" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/test/debug" isTestSource="true" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/test/debug" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/test/debug" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/res" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/resources" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/assets" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/aidl" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/java" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/jni" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/rs" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/res" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/assets" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/aidl" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/rs" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/res" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/resources" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/assets" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/aidl" isTestSource="true" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/java" isTestSource="true" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/jni" isTestSource="true" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/rs" isTestSource="true" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/assets" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/bundles" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/classes" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/coverage-instrumented-classes" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dependency-cache" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex-cache" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/jacoco" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/javaResources" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/libs" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/lint" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/manifests" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/ndk" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/pre-dexed" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/proguard" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/res" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/rs" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/symbols" />
- <excludeFolder url="file://$MODULE_DIR$/build/native-libs" />
- <excludeFolder url="file://$MODULE_DIR$/build/outputs" />
- <excludeFolder url="file://$MODULE_DIR$/build/tmp" />
- </content>
- <orderEntry type="jdk" jdkName="Android API 21 Platform" jdkType="Android SDK" />
- <orderEntry type="sourceFolder" forTests="false" />
- </component>
-</module>
-
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-apply plugin: 'com.android.library'
-
-android {
- compileSdkVersion 21
- buildToolsVersion "20.0.0"
- archivesBaseName = "iotivity"
-
- libraryVariants.all { variant ->
- variant.outputs.each { output ->
- def outputFile = output.outputFile
- if (outputFile != null && outputFile.name.endsWith('.aar')) {
- def fileName = "${archivesBaseName}-${TARGET_ARCH}-${outputFile.name}"
- output.outputFile = new File(outputFile.parent, fileName)
- }
- }
- }
-
- defaultConfig {
- minSdkVersion 21
- targetSdkVersion 21
- versionCode 1
- versionName "1.0"
- }
- buildTypes {
- release {
- proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
- }
- }
-
- lintOptions {
- abortOnError false
- }
-
- sourceSets {
- main {
- manifest.srcFile 'src/main/AndroidManifest.xml'
- jni.srcDirs = [] //disable automatic ndk-build call
- jniLibs.srcDir new File(buildDir, 'native-libs')
- }
- androidTest.setRoot('src/androidTest')
- }
-}
-
-
-dependencies {
- compile fileTree(dir: 'libs', include: ['*.jar'])
-
- androidTestCompile 'com.google.dexmaker:dexmaker-mockito:1.0'
- androidTestCompile 'com.google.dexmaker:dexmaker:1.0'
- androidTestCompile 'org.mockito:mockito-core:1.10.19'
-}
-
-////////////////
-////NDK Support
-////////////////
-//If using this, Android studio will fail run the following to set the environment variable for android studio:
-//launchctl setenv ANDROID_NDK_HOME
-//otherwise remove the dependsOn part and run ./gradlew buildNative from the command line
-task copyNativeLibs(type: Copy, dependsOn: 'buildNative') {
- dependsOn 'buildNative'
- from(new File('src/main/libs')) { include '**/*.so' exclude '**/libgnustl_shared.so' }
- into new File(buildDir, 'native-libs')
-}
-
-tasks.withType(JavaCompile) { compileTask -> compileTask.dependsOn copyNativeLibs }
-
-clean.dependsOn 'cleanCopyNativeLibs'
-
-tasks.withType(com.android.build.gradle.tasks.PackageApplication) {
- pkgTask ->
- pkgTask.jniFolders = new HashSet<File>()
- pkgTask.jniFolders.add(new File(buildDir, 'native-libs'))
-}
-
-task buildNative(type: Exec) {
- if (System.env.ANDROID_NDK_HOME != null) {
- //for windows use 'ndk-build.cmd'
- //def ndkBuild = new File(System.env.ANDROID_NDK_HOME, 'ndk-build.cmd')
- def ndkBuild = new File(System.env.ANDROID_NDK_HOME, 'ndk-build')
- commandLine ndkBuild, "APP_ABI=$TARGET_ARCH", "APP_OPTIM=$RELEASE", '-C', file('src/main').absolutePath
- } else {
- println '##################'
- println 'Skipping NDK build'
- println 'Reason: ANDROID_NDK_HOME not set.'
- println '##################'
- }
-}
+++ /dev/null
-# Add project specific ProGuard rules here.
-# By default, the flags in this file are appended to flags specified
-# in C:/android/sdk/tools/proguard/proguard-android.txt
-# You can edit the include path and order by changing the proguardFiles
-# directive in build.gradle.
-#
-# For more details, see
-# http://developer.android.com/guide/developing/tools/proguard.html
-
-# Add any project specific keep options here:
-
-# If your project uses WebView with JS, uncomment the following
-# and specify the fully qualified class name to the JavaScript interface
-# class:
-#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
-# public *;
-#}
+++ /dev/null
-package org.iotivity.service;
-
-import static org.iotivity.service.client.RcsRemoteResourceObject.CacheState;
-import static org.iotivity.service.client.RcsRemoteResourceObject.OnCacheUpdatedListener;
-import static org.iotivity.service.client.RcsRemoteResourceObject.OnRemoteAttributesReceivedListener;
-import static org.iotivity.service.client.RcsRemoteResourceObject.OnStateChangedListener;
-import static org.iotivity.service.client.RcsRemoteResourceObject.ResourceState;
-import static org.mockito.Matchers.anyInt;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.any;
-import static org.mockito.Mockito.timeout;
-import static org.mockito.Mockito.verify;
-
-import org.mockito.Mockito;
-
-public class RemoteResourceObjectTest extends TestBase {
-
- private RcsResourceAttributes createAttrs() {
- RcsResourceAttributes attrs = new RcsResourceAttributes();
- attrs.put("key", new RcsValue(3));
- attrs.put("b", new RcsValue(new RcsResourceAttributes()));
- attrs.put("myKey", new RcsValue("string-value"));
-
- return attrs;
- }
-
- public void testGetRemoteAttributesGetsAttributesOfServer()
- throws RcsException {
- OnRemoteAttributesReceivedListener listener = Mockito
- .mock(OnRemoteAttributesReceivedListener.class);
-
- setServerAttrbutes(createAttrs());
-
- mClient.getRemoteAttributes(listener);
-
- verify(listener, timeout(1000)).onAttributesReceived(eq(createAttrs()),
- anyInt());
- }
-
- public void testGetRemoteAttributesSetsAttributesOfServer()
- throws RcsException {
- OnRemoteAttributesReceivedListener listener = Mockito
- .mock(OnRemoteAttributesReceivedListener.class);
-
- mServer.setAttribute("key", new RcsValue(0));
-
- RcsResourceAttributes attrs = new RcsResourceAttributes();
- attrs.put("key", new RcsValue(3));
-
- mClient.setRemoteAttributes(attrs, listener);
-
- verify(listener, timeout(1000)).onAttributesReceived(
- any(RcsResourceAttributes.class), anyInt());
-
- assertEquals(3, mServer.getAttributeValue("key").asInt());
- }
-
- public void testMonitoringIsNotStartedByDefault() throws RcsException {
- assertFalse(mClient.isMonitoring());
- }
-
- public void testIsMonitoringReturnsTrueAfterStartMonitoring()
- throws RcsException {
- OnStateChangedListener listener = Mockito
- .mock(OnStateChangedListener.class);
- mClient.startMonitoring(listener);
-
- assertTrue(mClient.isMonitoring());
- }
-
- public void testStartMonitoringThrowsIfTryingToStartAgain()
- throws RcsException {
- OnStateChangedListener listener = Mockito
- .mock(OnStateChangedListener.class);
- mClient.startMonitoring(listener);
-
- try {
- mClient.startMonitoring(listener);
- fail("No exception thrown");
- } catch (RcsIllegalStateException e) {
- }
- }
-
- public void testDefaultResourceStateIsNone() throws RcsException {
- assertEquals(ResourceState.NONE, mClient.getState());
- }
-
- public void testCachingIsNotStartedByDefault() throws RcsException {
- assertFalse(mClient.isCaching());
- }
-
- public void testIsCachingReturnsTrueAfterStartCaching()
- throws RcsException {
- mClient.startCaching();
-
- assertTrue(mClient.isCaching());
- }
-
- public void testStartCachingThrowsIfTryingToStartAgain()
- throws RcsException {
- mClient.startCaching();
-
- try {
- mClient.startCaching();
- fail("No exception thrown");
- } catch (RcsIllegalStateException e) {
- }
- }
-
- public void testDefaultCacheStateIsNone() throws RcsException {
- assertEquals(CacheState.NONE, mClient.getCacheState());
- }
-
- public void testCacheStateIsUnreadyAfterStartCaching() throws RcsException {
- mClient.startCaching();
-
- assertEquals(CacheState.UNREADY, mClient.getCacheState());
- }
-
- public void testCacheStateIsReadyAfterCacheUpdated() throws RcsException {
- OnCacheUpdatedListener listener = Mockito
- .mock(OnCacheUpdatedListener.class);
- mClient.startCaching(listener);
-
- verify(listener, timeout(1000))
- .onCacheUpdated(any(RcsResourceAttributes.class));
-
- assertEquals(CacheState.READY, mClient.getCacheState());
- }
-
- public void testIsCachedAvailableReturnsTrueWhenCacheIsReady()
- throws RcsException {
- OnCacheUpdatedListener listener = Mockito
- .mock(OnCacheUpdatedListener.class);
- mClient.startCaching(listener);
-
- verify(listener, timeout(1000))
- .onCacheUpdated(any(RcsResourceAttributes.class));
-
- assertTrue(mClient.isCachedAvailable());
- }
-
- public void testGetCachedAttributesThrowsIfCachingIsNotStarted()
- throws RcsException {
- try {
- mClient.getCachedAttributes();
- fail("No exception thrown");
- } catch (RcsIllegalStateException e) {
- }
- }
-
- public void testCachedAttributesHasSameAttributesWithServer()
- throws RcsException {
- setServerAttrbutes(createAttrs());
-
- OnCacheUpdatedListener listener = Mockito
- .mock(OnCacheUpdatedListener.class);
- mClient.startCaching(listener);
-
- verify(listener, timeout(1000))
- .onCacheUpdated(any(RcsResourceAttributes.class));
-
- assertEquals(createAttrs(), mClient.getCachedAttributes());
- }
-
- public void testGetCachedAttributeThrowsIfCachingIsNotStarted()
- throws RcsException {
- try {
- mClient.getCachedAttribute("some_key");
- fail("No exception thrown");
- } catch (RcsIllegalStateException e) {
- }
- }
-
- public void testGetCachedAttributeReturnsNullIfKeyIsInvalid()
- throws RcsException {
- OnCacheUpdatedListener listener = Mockito
- .mock(OnCacheUpdatedListener.class);
- mClient.startCaching(listener);
-
- verify(listener, timeout(1000))
- .onCacheUpdated(any(RcsResourceAttributes.class));
-
- assertNull(mClient.getCachedAttribute("some_key"));
- }
-
- public void testHasSameUriWithServer() throws RcsException {
- assertEquals(RESOURCEURI, mClient.getUri());
- }
-
- public void testHasSameTypeWithServer() throws RcsException {
- assertEquals(RESOURCETYPE, mClient.getTypes()[0]);
- }
-
- public void testHasSameInterfaceWithServer() throws RcsException {
- assertEquals(RESOURCEINTERFACE, mClient.getInterfaces()[0]);
- }
-
- public void testThrowsIfObjectIsDestroyed() throws RcsException {
- mClient.destroy();
-
- try {
- mClient.getUri();
- fail("No exception thrown");
- } catch (RcsDestroyedObjectException e) {
- }
- }
-}
+++ /dev/null
-package org.iotivity.service;
-
-import org.iotivity.service.server.RcsResourceObject;
-
-import android.test.InstrumentationTestCase;
-
-public class ResourceObjectBuilderTest extends InstrumentationTestCase {
- private static final String RESOURCEURI = "/a/TemperatureSensor";
- private static final String RESOURCETYPE = "oic.r.type";
- private static final String RESOURCEINTERFACE = "oic.if.baseline";
-
- private RcsResourceObject mObject;
-
- @Override
- protected void tearDown() throws Exception {
- super.tearDown();
-
- mObject.destroy();
- mObject = null;
- }
-
- public void testResourceServerHasPropertiesSetByBuilder()
- throws RcsException {
- mObject = new RcsResourceObject.Builder(RESOURCEURI, RESOURCETYPE,
- RESOURCEINTERFACE).setDiscoverable(false).setObservable(true)
- .build();
-
- assertTrue(mObject.isObservable());
- }
-
- public void testResourceServerHasAttrsSetByBuilder() throws RcsException {
- RcsResourceAttributes attrs = new RcsResourceAttributes();
- attrs.put("key", new RcsValue(100));
-
- mObject = new RcsResourceObject.Builder(RESOURCEURI, RESOURCETYPE,
- RESOURCEINTERFACE).setAttributes(attrs).build();
-
- assertEquals(new RcsValue(100), mObject.getAttributeValue("key"));
- }
-}
+++ /dev/null
-package org.iotivity.service;
-
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyInt;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.never;
-import static org.mockito.Mockito.timeout;
-import static org.mockito.Mockito.verify;
-
-import org.iotivity.service.client.RcsRemoteResourceObject.OnRemoteAttributesReceivedListener;
-import org.iotivity.service.server.RcsGetResponse;
-import org.iotivity.service.server.RcsRequest;
-import org.iotivity.service.server.RcsResourceObject.AutoNotifyPolicy;
-import org.iotivity.service.server.RcsResourceObject.GetRequestHandler;
-import org.iotivity.service.server.RcsResourceObject.OnAttributeUpdatedListener;
-import org.iotivity.service.server.RcsResourceObject.SetRequestHandler;
-import org.iotivity.service.server.RcsResourceObject.SetRequestHandlerPolicy;
-import org.iotivity.service.server.RcsSetResponse;
-import org.mockito.Mockito;
-
-public class ResourceObjectTest extends TestBase {
- private static final String NEW_KEY = "new" + KEY;
-
- private OnRemoteAttributesReceivedListener mOnRemoteAttributesReceivedListener;
- private SetRequestHandler mSetRequestHandler;
- private GetRequestHandler mGetRequestHandler;
- private OnAttributeUpdatedListener mOnAttributeUpdatedListener;
-
- private void setSetRequestHandlerReturn(RcsSetResponse setResponse) {
- doReturn(setResponse).when(mSetRequestHandler).onSetRequested(
- any(RcsRequest.class), any(RcsResourceAttributes.class));
- }
-
- private void setGetRequestHandlerReturn(RcsGetResponse getResponse) {
- doReturn(getResponse).when(mGetRequestHandler).onGetRequested(
- any(RcsRequest.class), any(RcsResourceAttributes.class));
- }
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
-
- mOnRemoteAttributesReceivedListener = Mockito
- .mock(OnRemoteAttributesReceivedListener.class);
-
- mGetRequestHandler = Mockito.mock(GetRequestHandler.class);
- mSetRequestHandler = Mockito.mock(SetRequestHandler.class);
- mOnAttributeUpdatedListener = Mockito
- .mock(OnAttributeUpdatedListener.class);
- }
-
- public void testDefalutAutoNotifyPolicyIsUpdated() throws RcsException {
- assertEquals(AutoNotifyPolicy.UPDATED, mServer.getAutoNotifyPolicy());
- }
-
- public void testAutoNotifyPolicyCanBeSet() throws RcsException {
- mServer.setAutoNotifyPolicy(AutoNotifyPolicy.NEVER);
- assertEquals(AutoNotifyPolicy.NEVER, mServer.getAutoNotifyPolicy());
-
- mServer.setAutoNotifyPolicy(AutoNotifyPolicy.UPDATED);
- assertEquals(AutoNotifyPolicy.UPDATED, mServer.getAutoNotifyPolicy());
-
- mServer.setAutoNotifyPolicy(AutoNotifyPolicy.ALWAYS);
- assertEquals(AutoNotifyPolicy.ALWAYS, mServer.getAutoNotifyPolicy());
- }
-
- public void testDefalutSetRequestHandlerPolicyIsNever()
- throws RcsException {
- assertEquals(SetRequestHandlerPolicy.NEVER,
- mServer.getSetRequestHandlerPolicy());
- }
-
- public void testSetRequestHandlerPolicyCanBeSet() throws RcsException {
- mServer.setSetRequestHandlerPolicy(SetRequestHandlerPolicy.ACCEPT);
- assertEquals(SetRequestHandlerPolicy.ACCEPT,
- mServer.getSetRequestHandlerPolicy());
-
- mServer.setSetRequestHandlerPolicy(SetRequestHandlerPolicy.NEVER);
- assertEquals(SetRequestHandlerPolicy.NEVER,
- mServer.getSetRequestHandlerPolicy());
- }
-
- public void testGetRequestHandlerCalledIfReceived() throws RcsException {
- setGetRequestHandlerReturn(RcsGetResponse.defaultAction());
-
- mServer.setGetRequestHandler(mGetRequestHandler);
-
- mClient.getRemoteAttributes(mOnRemoteAttributesReceivedListener);
-
- verify(mGetRequestHandler, timeout(1000)).onGetRequested(
- any(RcsRequest.class), any(RcsResourceAttributes.class));
- }
-
- public void testGetRequestHandlerCanReturnCustomAttrsAsResponse()
- throws RcsException {
- RcsResourceAttributes newAttrs = new RcsResourceAttributes();
- newAttrs.put(NEW_KEY, new RcsValue(RAW_VALUE + 1));
-
- setGetRequestHandlerReturn(RcsGetResponse.create(newAttrs));
-
- mServer.setGetRequestHandler(mGetRequestHandler);
- mClient.getRemoteAttributes(mOnRemoteAttributesReceivedListener);
-
- verify(mGetRequestHandler, timeout(1000)).onGetRequested(
- any(RcsRequest.class), any(RcsResourceAttributes.class));
-
- verify(mOnRemoteAttributesReceivedListener, timeout(1000))
- .onAttributesReceived(eq(newAttrs), anyInt());
- }
-
- public void testSetRequestHandlerCalledIfReceived() throws RcsException {
- setSetRequestHandlerReturn(RcsSetResponse.defaultAction());
-
- mServer.setSetRequestHandler(mSetRequestHandler);
-
- mClient.setRemoteAttributes(new RcsResourceAttributes(),
- mOnRemoteAttributesReceivedListener);
-
- verify(mSetRequestHandler, timeout(1000)).onSetRequested(
- any(RcsRequest.class), any(RcsResourceAttributes.class));
- }
-
- public void testIgnoreSetRequestIfSetRequestHandlerReturnsIgnore()
- throws RcsException {
- setSetRequestHandlerReturn(RcsSetResponse.ignore());
-
- mServer.setSetRequestHandler(mSetRequestHandler);
-
- RcsResourceAttributes newAttrs = new RcsResourceAttributes();
- newAttrs.put(KEY, new RcsValue(RAW_VALUE + 1));
-
- mClient.setRemoteAttributes(newAttrs,
- mOnRemoteAttributesReceivedListener);
-
- verify(mSetRequestHandler, timeout(1000))
- .onSetRequested(any(RcsRequest.class), eq(newAttrs));
-
- assertEquals(RAW_VALUE, mServer.getAttributeValue(KEY).asInt());
- }
-
- public void testAcceptSetRequestIfSetRequestHandlerReturnsAccept()
- throws RcsException {
- setSetRequestHandlerReturn(RcsSetResponse.accept());
-
- mServer.setSetRequestHandlerPolicy(SetRequestHandlerPolicy.NEVER);
- mServer.setSetRequestHandler(mSetRequestHandler);
-
- RcsResourceAttributes newAttrs = new RcsResourceAttributes();
- newAttrs.put(NEW_KEY, new RcsValue(RAW_VALUE + 1));
-
- mClient.setRemoteAttributes(newAttrs,
- mOnRemoteAttributesReceivedListener);
-
- verify(mSetRequestHandler, timeout(1000))
- .onSetRequested(any(RcsRequest.class), eq(newAttrs));
-
- assertEquals(RAW_VALUE + 1, mServer.getAttributeValue(NEW_KEY).asInt());
- }
-
- public void testSetRequestHandlerCanReturnCustomAttrsAsResponse()
- throws RcsException {
- final RcsResourceAttributes newAttrs = new RcsResourceAttributes();
- newAttrs.put(NEW_KEY, new RcsValue(RAW_VALUE + 1));
-
- setSetRequestHandlerReturn(RcsSetResponse.create(newAttrs));
-
- mServer.setSetRequestHandler(mSetRequestHandler);
- mClient.setRemoteAttributes(new RcsResourceAttributes(),
- mOnRemoteAttributesReceivedListener);
-
- verify(mSetRequestHandler, timeout(1000)).onSetRequested(
- any(RcsRequest.class), any(RcsResourceAttributes.class));
-
- verify(mOnRemoteAttributesReceivedListener, timeout(1000))
- .onAttributesReceived(eq(newAttrs), anyInt());
- }
-
- public void testOnAttributeUpdatedListenerIsCalledIfValueUpdated()
- throws RcsException {
- final RcsValue newValue = new RcsValue(RAW_VALUE + 1);
- final RcsResourceAttributes newAttrs = new RcsResourceAttributes();
- newAttrs.put(KEY, newValue);
-
- mServer.addAttributeUpdatedListener(KEY, mOnAttributeUpdatedListener);
- mClient.setRemoteAttributes(newAttrs,
- mOnRemoteAttributesReceivedListener);
-
- verify(mOnAttributeUpdatedListener, timeout(1000))
- .onAttributeUpdated(eq(VALUE), eq(newValue));
- }
-
- public void testOnAttributeUpdatedListenerIsNotCalledIRemoved()
- throws RcsException {
- final RcsValue newValue = new RcsValue(RAW_VALUE + 1);
- final RcsResourceAttributes newAttrs = new RcsResourceAttributes();
- newAttrs.put(KEY, newValue);
-
- mServer.addAttributeUpdatedListener(KEY, mOnAttributeUpdatedListener);
- mServer.removeAttribute(KEY);
- mClient.setRemoteAttributes(newAttrs,
- mOnRemoteAttributesReceivedListener);
-
- verify(mOnAttributeUpdatedListener, never())
- .onAttributeUpdated(eq(VALUE), eq(newValue));
- }
-
- public void testThrowIfObjectIsDestroyed() throws RcsException {
- mServer.destroy();
- try {
- mServer.removeAttribute("");
- fail("No exception thrown");
- } catch (RcsDestroyedObjectException e) {
- }
-
- }
-}
+++ /dev/null
-package org.iotivity.service;
-
-import org.iotivity.service.client.RcsAddress;
-import org.iotivity.service.client.RcsDiscoveryManager;
-import org.iotivity.service.client.RcsDiscoveryManager.OnResourceDiscoveredListener;
-import org.iotivity.service.client.RcsRemoteResourceObject;
-import org.iotivity.service.server.RcsResourceObject;
-
-import android.test.InstrumentationTestCase;
-
-public abstract class TestBase extends InstrumentationTestCase {
- protected static final String RESOURCEURI = "/a/TemperatureSensor";
- protected static final String RESOURCETYPE = "oic.r.type";
- protected static final String RESOURCEINTERFACE = "oic.if.baseline";
-
- protected static final String KEY = "key";
- protected static final RcsValue VALUE = new RcsValue(100);
- protected static final int RAW_VALUE = 100;
-
- private final Object mCond = new Object();
-
- protected RcsResourceObject mServer;
- protected RcsRemoteResourceObject mClient;
-
- private OnResourceDiscoveredListener mOnResourceDiscoveredListener = new OnResourceDiscoveredListener() {
- @Override
- public void onResourceDiscovered(
- RcsRemoteResourceObject remoteObject) {
- if (mClient != null) {
- return;
- }
-
- mClient = remoteObject;
- synchronized (mCond) {
- mCond.notify();
- }
- }
- };
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
-
- mServer = new RcsResourceObject.Builder(RESOURCEURI, RESOURCETYPE,
- RESOURCEINTERFACE).build();
- mServer.setAttribute(KEY, VALUE);
-
- WaitUntilDiscovered();
-
- assertNotNull(mClient);
- }
-
- private void WaitUntilDiscovered() throws RcsException {
- while (mClient == null) {
- try {
- RcsDiscoveryManager.DiscoveryTask discoveryTask = RcsDiscoveryManager
- .getInstance().discoverResourceByType(RcsAddress.multicast(),
- RESOURCETYPE, mOnResourceDiscoveredListener);
-
- synchronized (mCond) {
- mCond.wait(100);
- }
-
- discoveryTask.cancel();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
-
- protected void setServerAttrbutes(RcsResourceAttributes attrs)
- throws RcsException {
- RcsResourceObject.AttributesLock lock = mServer.getAttributesLock();
-
- try {
- lock.lock().putAll(attrs);
- lock.apply();
- } finally {
- lock.unlock();
- }
- }
-
- @Override
- protected void tearDown() throws Exception {
- super.tearDown();
-
- mServer.destroy();
- mClient.destroy();
- }
-}
+++ /dev/null
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="org.iotivity.service" />
\ No newline at end of file
+++ /dev/null
-package org.iotivity.service;
-
-/**
- * This Class represents byte string value for RcsResourceAttributes.
- */
-public class RcsByteString {
-
- private byte[] mData;
- private long mSize;
-
- public RcsByteString(byte[] data, long size) {
- this.mData = data;
- this.mSize = size;
- }
-
- public byte[] getValue() {
- return this.mData;
- }
-
- public long getSize() {
- return this.mSize;
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.iotivity.service;
-
-/**
- * Thrown when trying to access a destroyed resource object.
- *
- */
-public class RcsDestroyedObjectException extends RcsException {
-
- private static final long serialVersionUID = -4107062696447237658L;
-
- public RcsDestroyedObjectException(String message) {
- super(message);
- }
-
-}
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-package org.iotivity.service;
-
-/**
- * An exception that indicates there was an error with execution of Rcs APIs.
- */
-public class RcsException extends Exception {
-
- private static final long serialVersionUID = 7044421943523001940L;
-
- public RcsException(String message) {
- super(message);
- }
-}
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-package org.iotivity.service;
-
-/**
- * Thrown when an action is attempted at a time when not in the correct state.
- *
- */
-public class RcsIllegalStateException extends RcsException {
-
- private static final long serialVersionUID = 6142669404885957616L;
-
- public RcsIllegalStateException(String message) {
- super(message);
- }
-
-}
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-package org.iotivity.service;
-
-public class RcsObject {
- static {
- System.loadLibrary("gnustl_shared");
- System.loadLibrary("oc_logger");
- System.loadLibrary("connectivity_abstraction");
- System.loadLibrary("ca-interface");
- System.loadLibrary("octbstack");
- System.loadLibrary("oc");
- System.loadLibrary("rcs_client");
- System.loadLibrary("rcs_server");
- System.loadLibrary("rcs_common");
- System.loadLibrary("rcs_jni");
- }
-
- private long mNativeHandle;
-
- private native void nativeDispose();
-
- protected RcsObject() {
- }
-
- @Override
- protected void finalize() throws Throwable {
- super.finalize();
-
- dispose();
- }
-
- protected void dispose() {
- if (mNativeHandle != 0L) nativeDispose();
- }
-
- protected boolean hasHandle() {
- return mNativeHandle != 0L;
- }
-}
+++ /dev/null
-package org.iotivity.service;
-
-/**
- * Thrown when an operation that has base-layer dependency is failed.
- *
- */
-public class RcsPlatformException extends RcsException {
-
- private static final long serialVersionUID = -6093438347973754721L;
-
- private final int mReasonCode;
-
- public RcsPlatformException(String message, int reasonCode) {
- super(message);
-
- mReasonCode = reasonCode;
- }
-
- public int getReasonCode() {
- return mReasonCode;
- }
-}
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-package org.iotivity.service;
-
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-
-import org.iotivity.service.server.RcsLockedAttributes;
-
-/**
- *
- * This class represents the attributes for a resource.
- *
- * @see RcsValue
- */
-public final class RcsResourceAttributes extends RcsObject {
-
- private native boolean nativeIsEmpty();
-
- private native int nativeSize();
-
- private native boolean nativeRemove(String key);
-
- private native void nativeClear();
-
- private native boolean nativeContains(String key);
-
- private native void nativeAddKeys(Set<String> set);
-
- private native RcsValue nativeExtract(String key);
-
- private native void nativeExtractAll(Map<String, RcsValue> map);
-
- private final Map<String, RcsValue> mCache = new HashMap<>();
-
- public RcsResourceAttributes() {
- }
-
- public RcsResourceAttributes(RcsLockedAttributes lockedAttrs)
- throws RcsException {
- for (final String key : lockedAttrs.keySet()) {
- mCache.put(key, lockedAttrs.get(key));
- }
- }
-
- /**
- * Returns a unmodifiable Set view of the keys contained in this attributes.
- *
- * @return an unmodifiable set view of the keys in this attributes
- */
- public Set<String> keySet() {
- if (hasHandle()) {
- final Set<String> keySet = new HashSet<>(mCache.keySet());
-
- nativeAddKeys(keySet);
-
- return Collections.unmodifiableSet(keySet);
- }
-
- return Collections.unmodifiableSet(mCache.keySet());
- }
-
- /**
- * Returns the value to which the specified key is mapped, or null if this
- * contains no mapping for the key.
- *
- * @param key
- * the key whose associated value is to be returned
- *
- * @return the value to which the specified key is mapped, or null if this
- * contains no mapping for the key
- *
- * @throws NullPointerException
- * if key is null
- */
- public RcsValue get(String key) {
- if (key == null) throw new NullPointerException("key is null");
-
- if (!mCache.containsKey(key) && hasHandle() && nativeContains(key)) {
- mCache.put(key, nativeExtract(key));
- }
- return mCache.get(key);
- }
-
- /**
- * Sets the specified value with the specified key.
- * If the object previously contained a mapping for the key, the old value
- * is replaced by the specified value.
- *
- * @param key
- * key with which the specified value is to be associated
- *
- * @param value
- * value to be associated with the specified key
- *
- * @throws NullPointerException
- * if key or value is null
- *
- */
- public void put(String key, RcsValue value) {
- if (key == null) throw new NullPointerException("key is null");
- if (value == null) throw new NullPointerException("value is null");
-
- mCache.put(key, value);
- if (hasHandle()) nativeRemove(key);
- }
-
- /**
- * Sets the specified value with the specified key.
- * If the object previously contained a mapping for the key, the old value
- * is replaced by the specified value.
- *
- * @param key
- * key with which the specified value is to be associated
- *
- * @param value
- * value to be associated with the specified key
- *
- * @throws NullPointerException
- * if key or value is null
- * @throws IllegalArgumentException
- * if object is not supported type by {@link RcsValue}
- */
- public void put(String key, Object object) {
- if (key == null) throw new NullPointerException("key is null");
-
- put(key, new RcsValue(object));
- }
-
- /**
- * Returns true if this contains no key-value mappings.
- *
- * @return true if this contains no key-value mappings
- */
- public boolean isEmpty() {
- return mCache.isEmpty() && (!hasHandle() || nativeIsEmpty());
- }
-
- /**
- * Returns the number of key-value mappings.
- *
- * @return the number of key-value mappings
- */
- public int size() {
- if (hasHandle()) return mCache.size() + nativeSize();
- return mCache.size();
- }
-
- /**
- * Removes the mapping for a key from this attributes if it is present.
- *
- * @param key
- * key whose mapping is to be removed
- *
- * @return true if the key is present and the the value mapped is removed.
- */
- public boolean remove(String key) {
- if (key == null) throw new NullPointerException("key is null");
-
- // XXX make sure both cache and native values to be removed.
- final boolean cacheRemove = mCache.remove(key) != null;
- final boolean nativeRemove = hasHandle() && nativeRemove(key);
-
- return cacheRemove || nativeRemove;
- }
-
- /**
- * Removes all of the mappings.
- */
- public void clear() {
- mCache.clear();
- nativeClear();
- }
-
- /**
- * Returns true if this contains a mapping for the specified key.
- *
- * @param key
- * key whose presence is to be tested
- *
- * @return true if this contains a mapping for the specified key.
- *
- * @throws NullPointerException
- * if key is null
- */
- public boolean contains(String key) {
- if (key == null) throw new NullPointerException("key is null");
-
- return mCache.containsKey(key) || nativeContains(key);
- }
-
- private void esnureAllExtracted() {
- if (hasHandle()) nativeExtractAll(mCache);
- }
-
- @Override
- public boolean equals(Object o) {
- if (o == this) return true;
- if (!(o instanceof RcsResourceAttributes)) return false;
-
- final RcsResourceAttributes rhs = (RcsResourceAttributes) o;
-
- esnureAllExtracted();
- rhs.esnureAllExtracted();
-
- return mCache.equals(rhs.mCache);
- }
-
- @Override
- public int hashCode() {
- esnureAllExtracted();
- return mCache.hashCode();
- }
-
-}
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-package org.iotivity.service;
-
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * Value holds a value among various types at a time.
- *
- * Type helps identify type information of Value.
- *
- * @see RcsResourceAttributes
- * @see Type
- */
-public final class RcsValue {
-
- private static class NullType {
- @Override
- public String toString() {
- return "";
- }
- }
-
- /**
- * Identifiers for types of Value.
- *
- * @see Type
- */
- public static enum TypeId {
- NULL, BOOLEAN, INTEGER, DOUBLE, STRING, BYTESTRING, ATTRIBUTES, ARRAY;
- }
-
- /**
- * A Helper class to identify types of Value.
- *
- * @see RcsResourceAttributes
- * @see RcsValue
- * @see TypeId
- */
- public static class Type {
- private final TypeId mTypeId;
-
- Type(TypeId typeId) {
- mTypeId = typeId;
- }
-
- /**
- * Returns type identifier.
- *
- * @return Identifier of type
- *
- * @see #getBaseTypeId(RcsValue.Type)
- */
- public final TypeId getId() {
- return mTypeId;
- }
-
- protected TypeId getBaseTypeId() {
- return mTypeId;
- }
-
- protected int getDepth() {
- return 0;
- }
-
- /**
- * Returns the type identifier of a base type of sequence.
- *
- * For non sequence types, it is equivalent to calling {@link #getId()}.
- *
- * @return identifier of type
- *
- * @see getDepth
- * @see getId
- */
- public static TypeId getBaseTypeId(Type t) {
- return t.getBaseTypeId();
- }
-
- /**
- * Returns the depth of a type.
- *
- * The return will be zero for non sequence types.
- *
- * @see getBaseTypeId
- */
- public static int getDepth(Type t) {
- return t.getDepth();
- }
-
- /**
- * Factory method to create Type instance from an object.
- * Note that object must be a supported type by RcsValue.
- *
- * @return An instance that has TypeId for obj.
- *
- * @throws NullPointerException
- * if obj is null.
- * @throws IllegalArgumentException
- * if obj is not supported type.
- *
- */
- public static Type typeOf(Object obj) {
- if (obj == null) {
- throw new NullPointerException("object is null");
- }
-
- return typeOf(obj.getClass());
- }
-
- /**
- * Factory method to create Type instance from a class.
- * Note that class must be a supported type by RcsValue.
- *
- * @return An instance that has TypeId for class.
- *
- * @throws NullPointerException
- * if cls is null.
- * @throws IllegalArgumentException
- * if cls is not supported type.
- *
- */
- public static Type typeOf(Class<?> cls) {
- if (cls == null) {
- throw new NullPointerException("class is null");
- }
-
- if (sTypes.containsKey(cls)) return sTypes.get(cls);
-
- throw new IllegalArgumentException(
- cls.getSimpleName() + " is not supported type.");
- }
- }
-
- private static class ArrayType extends Type {
- private final TypeId mBaseTypeId;
- private final int mDimension;
-
- ArrayType(TypeId baseTypeId, int dimension) {
- super(TypeId.ARRAY);
-
- mBaseTypeId = baseTypeId;
- mDimension = dimension;
- }
-
- @Override
- protected TypeId getBaseTypeId() {
- return mBaseTypeId;
- }
-
- @Override
- protected int getDepth() {
- return mDimension;
- }
- }
-
- private static final NullType sNullValue = new NullType();
-
- private static Map<Class<?>, Type> sTypes;
-
- private final Object mObject;
- private Type mType;
-
- static {
- final Map<Class<?>, Type> types = new HashMap<Class<?>, Type>();
-
- types.put(NullType.class, new Type(TypeId.NULL));
- types.put(Boolean.class, new Type(TypeId.BOOLEAN));
- types.put(Integer.class, new Type(TypeId.INTEGER));
- types.put(Double.class, new Type(TypeId.DOUBLE));
- types.put(String.class, new Type(TypeId.STRING));
- types.put(RcsByteString.class, new Type(TypeId.BYTESTRING));
- types.put(RcsResourceAttributes.class, new Type(TypeId.ATTRIBUTES));
-
- types.put(boolean[].class, new ArrayType(TypeId.BOOLEAN, 1));
- types.put(int[].class, new ArrayType(TypeId.INTEGER, 1));
- types.put(double[].class, new ArrayType(TypeId.DOUBLE, 1));
- types.put(String[].class, new ArrayType(TypeId.STRING, 1));
- types.put(RcsByteString[].class, new ArrayType(TypeId.BYTESTRING, 1));
- types.put(RcsResourceAttributes[].class,
- new ArrayType(TypeId.ATTRIBUTES, 1));
-
- types.put(boolean[][].class, new ArrayType(TypeId.BOOLEAN, 2));
- types.put(int[][].class, new ArrayType(TypeId.INTEGER, 2));
- types.put(double[][].class, new ArrayType(TypeId.DOUBLE, 2));
- types.put(String[][].class, new ArrayType(TypeId.STRING, 2));
- types.put(RcsByteString[][].class, new ArrayType(TypeId.BYTESTRING, 2));
- types.put(RcsResourceAttributes[][].class,
- new ArrayType(TypeId.ATTRIBUTES, 2));
-
- types.put(boolean[][][].class, new ArrayType(TypeId.BOOLEAN, 3));
- types.put(int[][][].class, new ArrayType(TypeId.INTEGER, 3));
- types.put(double[][][].class, new ArrayType(TypeId.DOUBLE, 3));
- types.put(String[][][].class, new ArrayType(TypeId.STRING, 3));
- types.put(RcsByteString[][][].class, new ArrayType(TypeId.BYTESTRING, 3));
- types.put(RcsResourceAttributes[][][].class,
- new ArrayType(TypeId.ATTRIBUTES, 3));
-
- sTypes = Collections.unmodifiableMap(types);
-
- }
-
- static boolean isSupportedType(Class<?> cls) {
- return sTypes.containsKey(cls);
- }
-
- static void verifySupportedType(Class<?> cls) {
- if (!isSupportedType(cls)) {
- throw new IllegalArgumentException(
- cls.getSimpleName() + " is not supported type.");
- }
- }
-
- /**
- * Constructs a new value with an object.
- *
- * @param value
- * An object
- *
- * @throws NullPointerException
- * if value is null.
- * @throws IllegalArgumentException
- * if value is not supported type.
- */
- public RcsValue(Object value) {
- if (value == null) throw new NullPointerException("value is null!");
-
- verifySupportedType(value.getClass());
-
- mObject = value;
- }
-
- /**
- * Constructs a new value that holds null value.
- *
- */
- public RcsValue() {
- this(sNullValue);
- }
-
- /**
- * Constructs a new value that holds a boolean value.
- *
- * @param value
- * a boolean
- */
- public RcsValue(boolean value) {
- this((Object) value);
- }
-
- /**
- * Constructs a new value that holds an int value.
- *
- * @param value
- * an int
- */
- public RcsValue(int value) {
- this((Object) value);
- }
-
- /**
- * Constructs a new value that holds a double value.
- *
- * @param value
- * a double
- */
- public RcsValue(double value) {
- this((Object) value);
- }
-
- /**
- * Constructs a new value that holds a String value.
- *
- * @param value
- * a String
- *
- * @throws NullPointerException
- * if value is null.
- */
- public RcsValue(String value) {
- this((Object) value);
- }
-
- /**
- * Constructs a new value that holds a RcsResourceAttributes value.
- *
- * @param value
- * a RcsResourceAttributes
- *
- * @throws NullPointerException
- * if value is null.
- */
- public RcsValue(RcsResourceAttributes value) {
- this((Object) value);
- }
-
- /**
- * Constructs a new value that holds a boolean array.
- *
- * @param value
- * a boolean array
- *
- * @throws NullPointerException
- * if value is null.
- */
- public RcsValue(boolean[] value) {
- this((Object) value);
- }
-
- /**
- * Constructs a new value that holds a two-dimensional boolean array.
- *
- * @param value
- * a two-dimensional boolean array
- *
- * @throws NullPointerException
- * if value is null.
- */
- public RcsValue(boolean[][] value) {
- this((Object) value);
- }
-
- /**
- * Constructs a new value that holds a three-dimensional boolean array.
- *
- * @param value
- * a three-dimensional boolean array
- *
- * @throws NullPointerException
- * if value is null.
- */
- public RcsValue(boolean[][][] value) {
- this((Object) value);
- }
-
- /**
- * Constructs a new value that holds an int array.
- *
- * @param value
- * an int array
- *
- * @throws NullPointerException
- * if value is null.
- */
- public RcsValue(int[] value) {
- this((Object) value);
- }
-
- /**
- * Constructs a new value that holds a two-dimensional int array.
- *
- * @param value
- * a two-dimensional int array
- *
- * @throws NullPointerException
- * if value is null.
- */
- public RcsValue(int[][] value) {
- this((Object) value);
- }
-
- /**
- * Constructs a new value that holds a three-dimensional int array.
- *
- * @param value
- * a three-dimensional int array
- *
- * @throws NullPointerException
- * if value is null.
- */
- public RcsValue(int[][][] value) {
- this((Object) value);
- }
-
- /**
- * Constructs a new value that holds a double array.
- *
- * @param value
- * a double array
- *
- * @throws NullPointerException
- * if value is null.
- */
- public RcsValue(double[] value) {
- this((Object) value);
- }
-
- /**
- * Constructs a new value that holds a two-dimensional double array.
- *
- * @param value
- * a two-dimensional double array
- *
- * @throws NullPointerException
- * if value is null.
- */
- public RcsValue(double[][] value) {
- this((Object) value);
- }
-
- /**
- * Constructs a new value that holds a three-dimensional double array.
- *
- * @param value
- * a three-dimensional double array
- *
- * @throws NullPointerException
- * if value is null.
- */
- public RcsValue(double[][][] value) {
- this((Object) value);
- }
-
- /**
- * Constructs a new value that holds a String array.
- *
- * @param value
- * a String array
- *
- * @throws NullPointerException
- * if value is null.
- */
- public RcsValue(String[] value) {
- this((Object) value);
- }
-
- /**
- * Constructs a new value that holds a two-dimensional String array.
- *
- * @param value
- * a two-dimensional String array
- *
- * @throws NullPointerException
- * if value is null.
- */
- public RcsValue(String[][] value) {
- this((Object) value);
- }
-
- /**
- * Constructs a new value that holds a three-dimensional String array.
- *
- * @param value
- * a three-dimensional String array
- *
- * @throws NullPointerException
- * if value is null.
- */
- public RcsValue(String[][][] value) {
- this((Object) value);
- }
-
- /**
- * Constructs a new value that holds a RcsResourceAttributes array.
- *
- * @param value a RcsByteString array
- * @throws NullPointerException if value is null.
- */
- public RcsValue(RcsByteString[] value) {
- this((Object) value);
- }
-
- /**
- * Constructs a new value that holds a two-dimensional RcsByteString array.
- *
- * @param value a two-dimensional RcsByteString array
- * @throws NullPointerException if value is null.
- */
- public RcsValue(RcsByteString[][] value) {
- this((Object) value);
- }
-
- /**
- * Constructs a new value that holds a three-dimensional RcsByteString array.
- *
- * @param value a three-dimensional RcsByteString array
- * @throws NullPointerException if value is null.
- */
- public RcsValue(RcsByteString[][][] value) {
- this((Object) value);
- }
-
- /**
- * Constructs a new value that holds a RcsResourceAttributes array.
- *
- * @throws NullPointerException
- * if value is null.
- */
- public RcsValue(RcsResourceAttributes[] value) {
- this((Object) value);
- }
-
- /**
- * Constructs a new value that holds a two-dimensional RcsResourceAttributes
- * array.
- *
- * @param value
- * a two-dimensional RcsResourceAttributes array
- *
- * @throws NullPointerException
- * if value is null.
- */
- public RcsValue(RcsResourceAttributes[][] value) {
- this((Object) value);
- }
-
- /**
- * Constructs a new value that holds a three-dimensional
- * RcsResourceAttributes array.
- *
- * @param value
- * a three-dimensional RcsResourceAttributes array
- *
- * @throws NullPointerException
- * if value is null.
- */
- public RcsValue(RcsResourceAttributes[][][] value) {
- this((Object) value);
- }
-
- /**
- * Returns whether the value is null.
- *
- * @return true if the value is null.
- */
- public boolean isNull() {
- return isNullObject(mObject);
- }
-
- /**
- * Returns whether the object represents null for RcsValue.
- *
- * @param o
- * an object to be tested
- *
- * @return true if the object represents null.
- */
- public static boolean isNullObject(Object o) {
- return o == sNullValue;
- }
-
- /**
- * Returns type information.
- *
- * @return type information for the value.
- */
- public Type getType() {
- if (mType == null) mType = Type.typeOf(mObject);
- return mType;
- }
-
- /**
- * Returns the value as T.
- *
- * @return a value as T
- *
- * @throws ClassCastException
- * if the value is not of T.
- */
- @SuppressWarnings("unchecked")
- public <T> T get() {
- return (T) mObject;
- }
-
- @SuppressWarnings("unchecked")
- private <T> T getOrNull() {
- try {
- return (T) mObject;
- } catch (final ClassCastException e) {
- return null;
- }
- }
-
- /**
- * Returns the value as an Object.
- *
- * @return an Object
- */
- public Object asObject() {
- return mObject;
- }
-
- /**
- * Returns the value as a boolean, false if the value is not the desired
- * type.
- *
- * @return a boolean value
- *
- */
- public boolean asBoolean() {
- return asBoolean(false);
- }
-
- /**
- * Returns the value as a boolean.
- *
- * @param defaultValue
- * value to return if the value is not boolean.
- *
- * @return a boolean value
- *
- */
- public boolean asBoolean(boolean defaultValue) {
- try {
- return get();
- } catch (final ClassCastException e) {
- return defaultValue;
- }
- }
-
- /**
- * Returns the value as an int, 0 if the value is not the desired type.
- *
- * @return an int value
- *
- */
- public int asInt() {
- return asInt(0);
- }
-
- /**
- * Returns the value as an int.
- *
- * @param defaultValue
- * value to return if the value is not int.
- *
- * @return an int value
- *
- */
- public int asInt(int defaultValue) {
- try {
- return get();
- } catch (final ClassCastException e) {
- return defaultValue;
- }
- }
-
- /**
- * Returns the value as a double, 0 if the value is not the desired type.
- *
- * @return a double value
- *
- */
- public double asDouble() {
- return asDouble(0);
- }
-
- /**
- * Returns the value as a double.
- *
- * @param defaultValue
- * value to return if the value is not double.
- *
- * @return a double value
- *
- */
- public double asDouble(double defaultValue) {
- try {
- return get();
- } catch (final ClassCastException e) {
- return defaultValue;
- }
- }
-
- /**
- * Returns the value as a string, null if the value is not the desired type.
- *
- * @return a string value
- *
- */
- public String asString() {
- return asString(null);
- }
-
- /**
- * Returns the value as a String.
- *
- * @param defaultValue
- * value to return if the value is not String.
- *
- * @return a String value
- *
- */
- public String asString(String defaultValue) {
- try {
- return get();
- } catch (final ClassCastException e) {
- return defaultValue;
- }
- }
-
- /**
- * Returns the value as a RcsResourceAttributes,
- * null if the value is not the desired type.
- *
- * @return a RcsResourceAttributes value
- *
- */
- public RcsResourceAttributes asAttributes() {
- return getOrNull();
- }
-
- /**
- * Returns the value as a boolean array, null if the value is not the
- * desired type.
- *
- * @return a boolean array
- *
- */
- public boolean[] asBooleanArray() {
- return getOrNull();
- }
-
- /**
- * Returns the value as a two-dimensional boolean array, null if the value
- * is not the desired type.
- *
- * @return a two-dimensional boolean array
- *
- */
- public boolean[][] asBoolean2DArray() {
- return getOrNull();
- }
-
- /**
- * Returns the value as a three-dimensional boolean array, null if the value
- * is not the desired type.
- *
- * @return a three-dimensional boolean array
- *
- */
- public boolean[][][] asBoolean3DArray() {
- return getOrNull();
- }
-
- /**
- * Returns the value as an int array, null if the value is not the
- * desired type.
- *
- * @return an int array
- *
- */
- public int[] asIntArray() {
- return getOrNull();
- }
-
- /**
- * Returns the value as a two-dimensional int array, null if the value
- * is not the desired type.
- *
- * @return a two-dimensional int array
- *
- */
- public int[][] asInt2DArray() {
- return getOrNull();
- }
-
- /**
- * Returns the value as a three-dimensional int array, null if the value
- * is not the desired type.
- *
- * @return a three-dimensional int array
- *
- */
- public int[][][] asInt3DArray() {
- return getOrNull();
- }
-
- /**
- * Returns the value as a double array, null if the value is not the
- * desired type.
- *
- * @return a double array
- *
- */
- public double[] asDoubleArray() {
- return getOrNull();
- }
-
- /**
- * Returns the value as a two-dimensional double array, null if the value
- * is not the desired type.
- *
- * @return a two-dimensional double array
- *
- */
- public double[][] asDouble2DArray() {
- return getOrNull();
- }
-
- /**
- * Returns the value as a three-dimensional double array, null if the value
- * is not the desired type.
- *
- * @return a three-dimensional double array
- *
- */
- public double[][][] asDouble3DArray() {
- return getOrNull();
- }
-
- /**
- * Returns the value as a string array, null if the value is not the
- * desired type.
- *
- * @return a string array
- *
- */
- public String[] asStringArray() {
- return getOrNull();
- }
-
- /**
- * Returns the value as a two-dimensional string array, null if the value
- * is not the desired type.
- *
- * @return a two-dimensional string array
- *
- */
- public String[][] asString2DArray() {
- return getOrNull();
- }
-
- /**
- * Returns the value as a three-dimensional string array, null if the value
- * is not the desired type.
- *
- * @return a three-dimensional string array
- *
- */
- public String[][][] asString3DArray() {
- return getOrNull();
- }
-
- /**
- * Returns the value as an RcsByteString array, null if the value is not the
- * desired type.
- *
- * @return an RcsByteString array
- */
- public RcsByteString[] asByteStringArray() {
- return getOrNull();
- }
-
- /**
- * Returns the value as a two-dimensional RcsByteString array, null if the
- * value is not the desired type.
- *
- * @return a two-dimensional RcsByteString array
- */
- public RcsByteString[][] asByteString2DArray() {
- return getOrNull();
- }
-
- /**
- * Returns the value as a three-dimensional RcsByteString array, null if the
- * value is not the desired type.
- *
- * @return a three-dimensional RcsByteString array
- */
- public RcsByteString[][][] asByteString3DArray() {
- return getOrNull();
- }
-
- /**
- * Returns the value as an attributes array, null if the value is not the
- * desired type.
- *
- * @return an attributes array
- *
- */
- public RcsResourceAttributes[] asAttributesArray() {
- return getOrNull();
- }
-
- /**
- * Returns the value as a two-dimensional attributes array, null if the
- * value is not the desired type.
- *
- * @return a two-dimensional attributes array
- *
- */
- public RcsResourceAttributes[][] asAttributes2DArray() {
- return getOrNull();
- }
-
- /**
- * Returns the value as a three-dimensional attributes array, null if the
- * value is not the desired type.
- *
- * @return a three-dimensional attributes array
- *
- */
- public RcsResourceAttributes[][][] asAttributes3DArray() {
- return getOrNull();
- }
-
- @Override
- public boolean equals(Object o) {
- if (o == this) return true;
- if (!(o instanceof RcsValue)) return false;
-
- final RcsValue rhs = (RcsValue) o;
-
- return mObject.equals(rhs.mObject);
- }
-
- @Override
- public int hashCode() {
- return mObject.hashCode();
- }
-
- @Override
- public String toString() {
- return mObject.toString();
- }
-
-}
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-package org.iotivity.service.client;
-
-/**
- * This is to specify a target address to discover.
- *
- * @see RcsDiscoveryManager
- */
-public final class RcsAddress {
- private final String mAddress;
-
- private RcsAddress(String addr) {
- mAddress = addr;
- }
-
- /**
- * Factory method for multicast.
- *
- */
- public static RcsAddress multicast() {
- return new RcsAddress(null);
- }
-
- /**
- * Factory method for unicast.
- *
- * @param address
- * A physical address for the target.
- *
- * @throws NullPointerException
- * If address is null.
- */
- public static RcsAddress unicast(String address) {
- if (address == null) throw new NullPointerException("address is null.");
- return new RcsAddress(address);
- }
-
- String getAddress() {
- return mAddress;
- }
-}
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-package org.iotivity.service.client;
-
-import org.iotivity.service.RcsException;
-import org.iotivity.service.RcsObject;
-import org.iotivity.service.RcsPlatformException;
-
-/**
- * This class contains the resource discovery methods.
- *
- * @see RcsRemoteResourceObject
- */
-public final class RcsDiscoveryManager {
-
- static {
- System.loadLibrary("gnustl_shared");
- System.loadLibrary("oc_logger");
- System.loadLibrary("connectivity_abstraction");
- System.loadLibrary("ca-interface");
- System.loadLibrary("octbstack");
- System.loadLibrary("oc");
- System.loadLibrary("rcs_client");
- System.loadLibrary("rcs_server");
- System.loadLibrary("rcs_common");
- System.loadLibrary("rcs_jni");
- }
-
- /**
- * This represents a task for discovery.
- *
- * The task must be canceled if no longer needed.
- *
- */
- public static class DiscoveryTask extends RcsObject {
- private DiscoveryTask() {
- }
-
- public void cancel() {
- dispose();
- }
- }
-
- /**
- * Interface definition for a callback to be invoked when a resource is
- * discovered.
- *
- */
- public interface OnResourceDiscoveredListener {
-
- /**
- * Called when a resource is discovered.
- *
- * @param rcsRemoteResourceObject
- * a discovered remote resource
- *
- */
- void onResourceDiscovered(
- RcsRemoteResourceObject rcsRemoteResourceObject);
-
- }
-
- private static final RcsDiscoveryManager sInstance = new RcsDiscoveryManager();
-
- private native DiscoveryTask nativeDiscoverResource(String address,
- String relativeUri, String resourceType,
- OnResourceDiscoveredListener listener);
-
- private RcsDiscoveryManager() {
- }
-
- public static RcsDiscoveryManager getInstance() {
- return sInstance;
- }
-
- /**
- * Requests discovery for the resource of interest, regardless of uri and
- * resource type
- *
- * @param address
- * the target address
- * @param listener
- * the listener to be invoked when a resource is discovered
- *
- * @return a task object indicating this request.
- *
- * @throws RcsPlatformException
- * if the operation failed.
- * @throws NullPointerException
- * if address or listener is null.
- *
- */
- public DiscoveryTask discoverResource(RcsAddress address,
- OnResourceDiscoveredListener listener) throws RcsException {
- return discoverResourceByType(address, null, null, listener);
- }
-
- /**
- * Requests discovery for the resource of interest, regardless of resource
- * type.
- *
- * @param address
- * the target address
- * @param uri
- * the relative uri of resource to be searched
- * @param listener
- * the listener to be invoked when a resource is discovered
- *
- * @return a task object indicating this request.
- *
- * @throws RcsPlatformException
- * if the operation failed.
- * @throws NullPointerException
- * if address or listener is null.
- *
- */
- public DiscoveryTask discoverResource(RcsAddress address, String uri,
- OnResourceDiscoveredListener listener) throws RcsException {
- return discoverResourceByType(address, uri, null, listener);
- }
-
- /**
- * Requests discovery for the resource of interest by resource type.
- *
- * @param address
- * the target address
- * @param resourceType
- * the resource type
- * @param listener
- * the listener to be invoked when a resource is discovered
- *
- * @return a task object indicating this request.
- *
- * @throws RcsPlatformException
- * if the operation failed.
- * @throws NullPointerException
- * if address or listener is null.
- *
- *
- */
- public DiscoveryTask discoverResourceByType(RcsAddress address,
- String resourceType, OnResourceDiscoveredListener listener)
- throws RcsException {
- return discoverResourceByType(address, null, resourceType, listener);
- }
-
- /**
- * Requests discovery for the resource of interest by resource type with
- * provided relative uri.
- *
- * @param address
- * the target address
- * @param uri
- * the relative uri of resource to be searched
- * @param resourceType
- * the resource type
- * @param listener
- * the listener to be invoked when a resource is discovered
- *
- * @return a task object indicating this request.
- *
- * @throws RcsPlatformException
- * if the operation failed.
- * @throws NullPointerException
- * if address or listener is null.
- *
- *
- */
- public DiscoveryTask discoverResourceByType(RcsAddress address, String uri,
- String resourceType, OnResourceDiscoveredListener listener)
- throws RcsException {
- if (listener == null) {
- throw new NullPointerException("listener is null.");
- }
- if (address == null) {
- throw new NullPointerException("address is null.");
- }
-
- return nativeDiscoverResource(address.getAddress(), uri, resourceType,
- listener);
- }
-
-}
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-package org.iotivity.service.client;
-
-import org.iotivity.service.RcsDestroyedObjectException;
-import org.iotivity.service.RcsException;
-import org.iotivity.service.RcsIllegalStateException;
-import org.iotivity.service.RcsObject;
-import org.iotivity.service.RcsPlatformException;
-import org.iotivity.service.RcsResourceAttributes;
-import org.iotivity.service.RcsValue;
-
-/**
- *
- * This represents a remote resource and provides simple ways to interact with
- * it.
- * Basically this is a client of a remote resource that runs on other device.
- *
- * The class supports features to help get information of a remote resource
- * such as monitoring and caching.
- *
- * @see RcsDiscoveryManager
- *
- */
-public final class RcsRemoteResourceObject extends RcsObject {
-
- private native boolean nativeIsMonitoring();
-
- private native boolean nativeIsCaching();
-
- private native boolean nativeIsObservable();
-
- private native void nativeStartMonitoring(OnStateChangedListener listener);
-
- private native void nativeStopMonitoring();
-
- private native ResourceState nativeGetState();
-
- private native void nativeStartCaching(OnCacheUpdatedListener listener);
-
- private native void nativeStopCaching();
-
- private native CacheState nativeGetCacheState();
-
- private native boolean nativeIsCachedAvailable();
-
- private native RcsResourceAttributes nativeGetCachedAttributes();
-
- private native void nativeGetRemoteAttributes(
- OnRemoteAttributesReceivedListener listener);
-
- private native void nativeSetRemoteAttributes(
- RcsResourceAttributes attributes,
- OnRemoteAttributesReceivedListener listener);
-
- private native String nativeGetUri();
-
- private native String nativeGetAddress();
-
- private native String[] nativeGetTypes();
-
- private native String[] nativeGetInterfaces();
-
- private RcsRemoteResourceObject() {
- }
-
- /**
- * This represents states of monitoring.
- *
- * @see #startMonitoring(OnStateChangedListener)
- * @see #getState()
- * @see OnStateChangedListener
- *
- */
- public enum ResourceState {
- /** Monitoring is not started. */
- NONE,
-
- /**
- * Monitoring is started and checking state is in progress.
- * This is the default state after startMonitoring.
- */
- REQUESTED,
-
- /** The resource is alive. */
- ALIVE,
-
- /** Failed to reach the resource. */
- LOST_SIGNAL,
-
- /** The resource is deleted. */
- DESTROYED
- }
-
- /**
- * This represents states of caching.
- *
- * @see #startCaching()
- * @see #getCacheState()
- */
- public enum CacheState {
- /** Caching is not started. */
- NONE,
-
- /**
- * Caching is started, but the data is not ready yet. This is
- * the default state after startCaching.
- */
- UNREADY,
-
- /** The data is ready. */
- READY,
-
- /** Failed to reach the resource. */
- LOST_SIGNAL
- }
-
- /**
- * Interface definition for a callback to be invoked when the cache is
- * updated.
- *
- * @see #startCaching(OnCacheUpdatedListener)
- */
- public interface OnCacheUpdatedListener {
-
- /**
- * Called when the cache is updated.
- *
- * @param attributes
- * the updated attributes
- *
- */
- public void onCacheUpdated(RcsResourceAttributes attributes);
-
- }
-
- /**
- * Interface definition for a callback to be invoked when the response of
- * getRemoteAttributes and setRemoteAttributes is received.
- *
- * @see #getRemoteAttributes(OnRemoteAttributesReceivedListener)
- * @see #setRemoteAttributes(RcsResourceAttributes,
- * OnRemoteAttributesReceivedListener)
- */
- public interface OnRemoteAttributesReceivedListener {
-
- /**
- * Called when a response for the getRemoteAttributes request or
- * setRemoteAttributes request is received.
- *
- * @param attributes
- * the resource attributes received from the remote resource
- *
- */
- public void onAttributesReceived(RcsResourceAttributes attributes,
- int errorCode);
-
- }
-
- /**
- * Interface definition for a callback to be invoked when the monitoring
- * state is changed.
- *
- * @see #startMonitoring(OnStateChangedListener)
- */
- public interface OnStateChangedListener {
-
- /**
- * Called when the monitoring state is changed.
- *
- * @param resourceState
- * updated state
- *
- */
- public void onStateChanged(ResourceState resourceState);
- }
-
- private void assertAlive() throws RcsException {
- if (!hasHandle()) {
- throw new RcsDestroyedObjectException(
- "The object is already destroyed!");
- }
- }
-
- /**
- * Returns whether monitoring is enabled.
- *
- * @return true if monitoring the resource.
- *
- * @throws RcsDestroyedObjectException
- * if the object is already destroyed
- *
- * @see #startMonitoring(OnStateChangedListener)
- */
- public boolean isMonitoring() throws RcsException {
- assertAlive();
- return nativeIsMonitoring();
- }
-
- /**
- * Returns whether caching is enabled.
- *
- * @return true if caching the resource.
- *
- * @throws RcsDestroyedObjectException
- * if the object is already destroyed
- *
- * @see #startCaching()
- * @see #startCaching(OnCacheUpdatedListener)
- *
- */
- public boolean isCaching() throws RcsException {
- assertAlive();
- return nativeIsCaching();
- }
-
- /**
- * Returns whether resource is observable.
- *
- * @return true if resource is observable.
- *
- * @throws RcsDestroyedObjectException
- * if the object is already destroyed
- *
- * @see org.iotivity.service.server.RcsResourceObject.Builder#setObservable(boolean)
- */
- public boolean isObservable() throws RcsException {
- assertAlive();
- return nativeIsObservable();
- }
-
- /**
- * Starts monitoring the resource.
- * <p>
- * Monitoring provides a feature to check the presence of a resource, even
- * when the server is not announcing Presence using startPresnece.
- *
- * @param listener
- * the listener to receive new state.
- *
- * @throws NullPointerException
- * if listener is null
- * @throws RcsIllegalStateException
- * if monitoring is already started
- * @throws RcsDestroyedObjectException
- * if the object is already destroyed
- *
- * @see ResourceState
- * @see #isMonitoring()
- * @see #stopMonitoring()
- */
- public void startMonitoring(OnStateChangedListener listener)
- throws RcsException {
- assertAlive();
- if (listener == null) {
- throw new NullPointerException("listener is null.");
- }
-
- nativeStartMonitoring(listener);
- }
-
- /**
- * Stops monitoring the resource.
- * <p>
- * It does nothing if monitoring is not started.
- *
- * @throws RcsDestroyedObjectException
- * if the object is already destroyed
- *
- * @see #startMonitoring(OnStateChangedListener)
- * @see #isMonitoring()
- */
- public void stopMonitoring() throws RcsException {
- assertAlive();
- nativeStopMonitoring();
- }
-
- /**
- * Returns the current state of the resource.
- *
- * @return ResourceState - current resource state
- *
- * @throws RcsDestroyedObjectException
- * if the object is already destroyed
- *
- * @see #startMonitoring(OnStateChangedListener)
- * @see #isMonitoring()
- * @see OnStateChangedListener
- */
- public ResourceState getState() throws RcsException {
- assertAlive();
- return nativeGetState();
- }
-
- /**
- * Starts caching attributes of the resource.
- *
- * This will start data caching for the resource. Once caching started it
- * will look for the data updation on the resource and updates the cache
- * data accordingly.
- * <p>
- * It is equivalent to calling {@link #startCaching(OnCacheUpdatedListener)}
- * with null.
- *
- * @throws RcsDestroyedObjectException
- * if the object is already destroyed
- *
- * @see #startCaching(OnCacheUpdatedListener)
- * @see #isCaching()
- * @see #getCacheState()
- * @see #getCachedAttribute(String)
- * @see #getCachedAttributes()
- * @see OnCacheUpdatedListener
- */
- public void startCaching() throws RcsException {
- assertAlive();
- startCaching(null);
- }
-
- /**
- * Starts caching attributes of the resource.
- *
- * This will start data caching for the resource. Once caching started it
- * will look for the data updation on the resource and updates the cache
- * data accordingly.
- *
- * @param listener
- * the listener to be notified when attributes are updated or
- * null if no need
- *
- * @throws RcsDestroyedObjectException
- * if the object is already destroyed
- *
- * @see #startCaching()
- * @see #isCaching()
- * @see #getCacheState()
- * @see #getCachedAttribute(String)
- * @see #getCachedAttributes()
- * @see OnCacheUpdatedListener
- */
- public void startCaching(OnCacheUpdatedListener listener)
- throws RcsException {
- assertAlive();
- nativeStartCaching(listener);
- }
-
- /**
- * Stops caching.
- *
- * It does nothing if caching is not started.
- *
- * @throws RcsDestroyedObjectException
- * if the object is already destroyed
- *
- * @see #startCaching()
- * @see #startCaching(OnCacheUpdatedListener)
- * @see #isCaching()
- *
- */
- public void stopCaching() throws RcsException {
- assertAlive();
- nativeStopCaching();
- }
-
- /**
- * Returns the current cache state.
- *
- * @return current cache state.
- *
- * @throws RcsDestroyedObjectException
- * if the object is already destroyed
- *
- * @see #startCaching()
- * @see #startCaching(OnCacheUpdatedListener)
- * @see #isCaching()
- */
- public CacheState getCacheState() throws RcsException {
- assertAlive();
- return nativeGetCacheState();
- }
-
- /**
- * Returns whether cached data is available.
- *
- * Cache will be available always once cache state had been
- * {@link CacheState#READY} even if current state is
- * {@link CacheState#LOST_SIGNAL} until stopped.
- *
- * @return true if cache data is available.
- *
- * @throws RcsDestroyedObjectException
- * if the object is already destroyed
- *
- * @see #startCaching()
- * @see #startCaching(OnCacheUpdatedListener)
- * @see #isCaching()
- * @see #getCacheState()
- *
- */
- public boolean isCachedAvailable() throws RcsException {
- assertAlive();
- return nativeIsCachedAvailable();
- }
-
- /**
- * Returns the cached attributes.
- * <p>
- * Note that this works only when cache is available.
- *
- * @return the cached attributes.
- *
- * @throws RcsIllegalStateException
- * if cache is not available
- * @throws RcsDestroyedObjectException
- * if the object is already destroyed
- *
- * @see #startCaching()
- * @see #startCaching(OnCacheUpdatedListener)
- * @see #isCaching()
- * @see #getCacheState()
- * @see #isCachedAvailable()
- * @see #getCachedAttribute(String)
- *
- */
- public RcsResourceAttributes getCachedAttributes() throws RcsException {
- assertAlive();
- return nativeGetCachedAttributes();
- }
-
- /**
- * Returns the cached value to which the specified key is mapped, or null if
- * no mapping for the key.
- * <p>
- * Note that this works only when cache is available.
- *
- * @param key
- * the key whose associated value is to be returned
- *
- * @return the value to which the specified key is mapped, or null if no
- * mapping for the key
- *
- * @throws NullPointerException
- * if key is null
- * @throws RcsIllegalStateException
- * if cache is not available
- * @throws RcsDestroyedObjectException
- * if the object is already destroyed
- *
- * @see #startCaching()
- * @see #startCaching(OnCacheUpdatedListener)
- * @see #isCaching()
- * @see #getCacheState()
- * @see #isCachedAvailable()
- * @see #getCachedAttributes()
- *
- */
- public RcsValue getCachedAttribute(String key) throws RcsException {
- assertAlive();
- if (key == null) {
- throw new NullPointerException("key is null.");
- }
-
- return getCachedAttributes().get(key);
- }
-
- /**
- * Sends a request for the resource attributes directly to the resource.
- *
- * @param listener
- * the listener to receive the response
- *
- * @throws NullPointerException
- * if listener is null
- * @throws RcsDestroyedObjectException
- * if the object is already destroyed
- * @throws RcsPlatformException
- * if the operation failed
- *
- * @see OnRemoteAttributesReceivedListener
- */
- public void getRemoteAttributes(OnRemoteAttributesReceivedListener listener)
- throws RcsException {
- assertAlive();
- if (listener == null) {
- throw new NullPointerException("listener is null.");
- }
-
- nativeGetRemoteAttributes(listener);
- }
-
- /**
- * Sends a set request with resource attributes to the resource.
- * <p>
- * The SetRequest behavior depends on the server, whether updating its
- * attributes or not.
- *
- * @param attributes
- * attributes to set for the remote resource.
- *
- * @throws NullPointerException
- * if attributes or listener is null
- * @throws RcsDestroyedObjectException
- * if the object is already destroyed
- * @throws RcsPlatformException
- * if the operation failed
- *
- * @see OnRemoteAttributesReceivedListener
- */
- public void setRemoteAttributes(RcsResourceAttributes attributes,
- OnRemoteAttributesReceivedListener listener) throws RcsException {
- assertAlive();
-
- if (attributes == null) {
- throw new NullPointerException("attributes is null.");
- }
- if (listener == null) {
- throw new NullPointerException("listener is null.");
- }
-
- nativeSetRemoteAttributes(attributes, listener);
- }
-
- /**
- * Returns the uri of the resource.
- *
- * @return uri of the resource
- *
- * @throws RcsDestroyedObjectException
- * if the object is already destroyed
- */
- public String getUri() throws RcsException {
- assertAlive();
- return nativeGetUri();
- }
-
- /**
- * Returns the address of the resource .
- *
- * @return address of the resource
- *
- * @throws RcsDestroyedObjectException
- * if the object is already destroyed
- */
- public String getAddress() throws RcsException {
- assertAlive();
- return nativeGetAddress();
- }
-
- /**
- * Returns the resource types of the resource.
- *
- * @return resource types
- *
- * @throws RcsDestroyedObjectException
- * if the object is already destroyed
- */
- public String[] getTypes() throws RcsException {
- assertAlive();
- return nativeGetTypes();
- }
-
- /**
- * Returns the resource interfaces of the resource.
- *
- * @return resource interfaces
- *
- * @throws RcsDestroyedObjectException
- * if the object is already destroyed
- */
- public String[] getInterfaces() throws RcsException {
- assertAlive();
- return nativeGetInterfaces();
- }
-
- /**
- * Reclaims all resources used by this object.
- * This must be called if the resource is not used any longer.
- *
- */
- public void destroy() {
- super.dispose();
- }
-}
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-package org.iotivity.service.server;
-
-import org.iotivity.service.RcsResourceAttributes;
-
-/**
- * This class provides methods to create the response for a get request.
- *
- * @see RcsResourceObject
- * @see RcsSetResponse
- */
-public class RcsGetResponse extends RcsResponse {
-
- /**
- * Creates a default RCcsGetResponse. The response will have
- * {@link #DEFAULT_ERROR_CODE} for the errorCode. The attributes of
- * {@link RcsResourceObject} will be set as the result attributes.
- *
- */
- public static RcsGetResponse defaultAction() {
- return new RcsGetResponse();
- }
-
- /**
- * Creates a RcsGetResponse with error code passed. The
- * attributes of the {@link RcsResourceObject} will be set as the result
- * attributes.
- *
- * @param errorCode
- * error code to be set in response
- *
- */
- public static RcsGetResponse create(int errorCode) {
- return new RcsGetResponse(errorCode);
-
- }
-
- /**
- * Creates a RcsGetResponse with custom attributes and
- * {@link #DEFAULT_ERROR_CODE} for the errorCode. This sends the passed
- * attributes as the result attributes instead of the one the
- * {@link RcsResourceObject} holds.
- *
- * @param attributes
- * attributes to be sent as the result
- *
- */
- public static RcsGetResponse create(RcsResourceAttributes attributes) {
- return new RcsGetResponse(attributes);
- }
-
- /**
- * Creates a RcsGetResponse with error code passed. This sends
- * the passed attributes as the result attributes instead of one the
- * {@link RcsResourceObject} holds.
- *
- * @param attributes
- * attributes to be sent as the result
- * @param errorCode
- * error code for response
- *
- */
- public static RcsGetResponse create(RcsResourceAttributes attributes,
- int errorCode) {
- return new RcsGetResponse(attributes, errorCode);
- }
-
- private RcsGetResponse() {
- super();
- }
-
- private RcsGetResponse(int errorCode) {
- super(errorCode);
- }
-
- private RcsGetResponse(RcsResourceAttributes attrs) {
- super(attrs);
- }
-
- private RcsGetResponse(RcsResourceAttributes attrs, int errorCode) {
- super(attrs, errorCode);
- }
-}
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-package org.iotivity.service.server;
-
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-
-import org.iotivity.service.RcsException;
-import org.iotivity.service.RcsObject;
-import org.iotivity.service.RcsResourceAttributes;
-import org.iotivity.service.RcsValue;
-
-public final class RcsLockedAttributes extends RcsObject {
-
- private static native boolean nativeIsEmpty(RcsResourceObject resourceObj);
-
- private static native int nativeSize(RcsResourceObject resourceObj);
-
- private static native boolean nativeRemove(RcsResourceObject resourceObj,
- String key);
-
- private static native boolean nativeClear(RcsResourceObject resourceObj);
-
- private static native boolean nativeContains(RcsResourceObject resourceObj,
- String key);
-
- private static native void nativeAddKeys(RcsResourceObject resourceObj,
- Set<String> set);
-
- private static native RcsValue nativeAsJavaObject(
- RcsResourceObject resourceObj, String key);
-
- private static native void nativeApply(RcsResourceObject resourceObj,
- Map<String, RcsValue> cache);
-
- private native void nativeLock(RcsResourceObject resourceObj);
-
- private native void nativeUnlock();
-
- private final RcsResourceObject mResourceObject;
-
- private boolean mIsUnlocked;
-
- private Map<String, RcsValue> mCache = new HashMap<>();
-
- RcsLockedAttributes(RcsResourceObject resourceObject) throws RcsException {
- if (resourceObject == null) {
- throw new RcsException("Illegal opertaion!");
- }
-
- mResourceObject = resourceObject;
-
- nativeLock(resourceObject);
- }
-
- void setUnlockState() {
- mIsUnlocked = true;
- mCache = null;
-
- nativeUnlock();
- }
-
- void apply() {
- nativeApply(mResourceObject, mCache);
- mCache.clear();
- }
-
- private void ensureLocked() throws RcsException {
- if (mIsUnlocked) {
- throw new RcsUnlockedException("This attributes is unlocked!");
- }
- }
-
- /**
- * Returns a unmodifiable Set view of the keys contained in this attributes.
- *
- * @return an unmodifiable set view of the keys in this attributes
- *
- * @throws RcsUnlockedException
- * if the {@link RcsResourceObject.AttributesLock} for this
- * object is unlocked
- */
- public Set<String> keySet() throws RcsException {
- ensureLocked();
-
- final Set<String> keySet = new HashSet<>(mCache.keySet());
-
- nativeAddKeys(mResourceObject, keySet);
-
- return Collections.unmodifiableSet(keySet);
- }
-
- /**
- * Returns the value to which the specified key is mapped, or null if this
- * contains no mapping for the key.
- *
- * @param key
- * the key whose associated value is to be returned
- *
- * @return the value to which the specified key is mapped, or null if this
- * contains no mapping for the key
- *
- * @throws NullPointerException
- * if key is null
- * @throws RcsUnlockedException
- * if the {@link RcsResourceObject.AttributesLock} for this
- * object is unlocked
- */
- public RcsValue get(String key) throws RcsException {
- ensureLocked();
-
- if (key == null) throw new NullPointerException("key is null");
-
- if (!mCache.containsKey(key) && nativeContains(mResourceObject, key)) {
- mCache.put(key, nativeAsJavaObject(mResourceObject, key));
- }
- return mCache.get(key);
- }
-
- /**
- * Copies all of the mappings from the specified to this
- *
- * @param attributes
- * attributes to be copied
- *
- * @throws RcsUnlockedException
- * if the {@link RcsResourceObject.AttributesLock} for this
- * object is unlocked
- *
- */
- public RcsLockedAttributes putAll(RcsResourceAttributes attributes)
- throws RcsException {
- ensureLocked();
-
- final Set<String> keys = attributes.keySet();
-
- for (final String k : keys) {
- mCache.put(k, attributes.get(k));
- }
- return this;
- }
-
- /**
- * Sets the specified value with the specified key.
- * If the object previously contained a mapping for the key, the old value
- * is replaced by the specified value.
- *
- * @param key
- * key with which the specified value is to be associated
- *
- * @param value
- * value to be associated with the specified key
- *
- * @throws NullPointerException
- * if key or value is null
- * @throws RcsUnlockedException
- * if the {@link RcsResourceObject.AttributesLock} for this
- * object is unlocked
- *
- */
- public RcsLockedAttributes put(String key, RcsValue value)
- throws RcsException {
- ensureLocked();
-
- if (key == null) throw new NullPointerException("key is null");
- if (value == null) throw new NullPointerException("value is null");
-
- mCache.put(key, value);
-
- return this;
- }
-
- /**
- * Sets the specified value with the specified key.
- * If the object previously contained a mapping for the key, the old value
- * is replaced by the specified value.
- *
- * @param key
- * key with which the specified value is to be associated
- *
- * @param value
- * value to be associated with the specified key
- *
- * @throws NullPointerException
- * if key or value is null
- * @throws IllegalArgumentException
- * if object is not supported type by {@link RcsValue}
- * @throws RcsUnlockedException
- * if the {@link RcsResourceObject.AttributesLock} for this
- * object is unlocked
- */
- public void put(String key, Object value) throws RcsException {
- if (key == null) throw new NullPointerException("key is null");
-
- put(key, new RcsValue(value));
- }
-
- /**
- * Returns whether attribute is empty.
- *
- * @throws RcsUnlockedException
- * if the {@link RcsResourceObject.AttributesLock} for this
- * object is unlocked
- */
- public boolean isEmpty() throws RcsException {
- ensureLocked();
-
- return mCache.isEmpty() && nativeIsEmpty(mResourceObject);
- }
-
- /**
- * Returns the number of key-value mappings.
- *
- * @throws RcsUnlockedException
- * if the {@link RcsResourceObject.AttributesLock} for this
- * object is unlocked
- */
- public int size() throws RcsException {
- ensureLocked();
-
- return mCache.size() + nativeSize(mResourceObject);
- }
-
- /**
- * Removes the mapping for a key from this attributes if it is present.
- *
- * @param key
- * key whose mapping is to be removed
- *
- * @return true if the key is present and the the value mapped is removed.
- *
- * @throws RcsUnlockedException
- * if the {@link RcsResourceObject.AttributesLock} for this
- * object is unlocked
- */
- public boolean remove(String key) throws RcsException {
- ensureLocked();
-
- if (key == null) throw new NullPointerException("key is null");
-
- // XXX make sure both cache and native values to be removed.
- final boolean cacheRemove = mCache.remove(key) != null;
- final boolean nativeRemove = nativeRemove(mResourceObject, key);
-
- return cacheRemove || nativeRemove;
- }
-
- /**
- * Removes all elements.
- *
- * @throws RcsUnlockedException
- * if the {@link RcsResourceObject.AttributesLock} for this
- * object is unlocked
- */
- public void clear() throws RcsException {
- ensureLocked();
-
- nativeClear(mResourceObject);
- }
-
- /**
- * Returns true if this contains a mapping for the specified key.
- *
- * @param key
- * key whose presence is to be tested
- *
- * @return true if this contains a mapping for the specified key.
- *
- * @throws NullPointerException
- * if key is null
- * @throws RcsUnlockedException
- * if the {@link RcsResourceObject.AttributesLock} for this
- * object is unlocked
- */
- public boolean contains(String key) throws RcsException {
- ensureLocked();
-
- if (key == null) throw new NullPointerException("key is null");
-
- return mCache.containsKey(key) || nativeContains(mResourceObject, key);
- }
-}
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-package org.iotivity.service.server;
-
-/**
- * This class describes the request.
- */
-public class RcsRequest {
-
- private final String mUri;
-
- private RcsRequest(String resourceUri) {
- mUri = resourceUri;
- }
-
- /**
- * Returns the URI of the request.
- *
- * @return Uri of the request in string form
- */
- public String getResourceUri() {
- return mUri;
- }
-}
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-/**
- * @file RCSResourceObject.java
- *
- * This file contains the resource object APIs provided to the developers.
- * RCSResourceObject is a part of the server builder module.
- *
- */
-
-package org.iotivity.service.server;
-
-import java.lang.ref.WeakReference;
-
-import org.iotivity.service.RcsDestroyedObjectException;
-import org.iotivity.service.RcsException;
-import org.iotivity.service.RcsIllegalStateException;
-import org.iotivity.service.RcsObject;
-import org.iotivity.service.RcsPlatformException;
-import org.iotivity.service.RcsResourceAttributes;
-import org.iotivity.service.RcsValue;
-
-/**
- * RCSResourceObject represents a resource. It handles any requests from clients
- * automatically with attributes.
- * <p>
- * It also provides an auto notification mechanism that notifies to the
- * observers. Requests are handled automatically by defaultAction of
- * {@link RcsGetResponse} and {@link RcsSetResponse}. You can override them and
- * send your own response with {@link GetRequestHandler} and
- * {@link SetRequestHandler}.
- * <p>
- * For simple resources, they are simply required to notify whenever attributes
- * are changed by a set request. In this case, add an
- * {@link OnAttributeUpdatedListener} with a key interested in instead of
- * overriding {@link SetRequestHandler}.
- *
- * @see Builder
- */
-public final class RcsResourceObject extends RcsObject {
- /**
- * This is a builder to create resource with properties and attributes.
- *
- * The resource will be observable and discoverable by default, to make them
- * disable
- * set these properties explicitly with setDiscoverable and setObservable.
- *
- */
- public static class Builder {
- private final String mUri;
- private final String mType;
- private final String mInterface;
- private boolean mIsObservable = true;
- private boolean mIsDiscovervable = true;
- private RcsResourceAttributes mAttributes;
-
- /**
- * Constructs a Builder.
- *
- * @param uri
- * resource uri
- * @param resourceType
- * resource type
- * @param resourceInterface
- * resource interface
- *
- * @throws NullPointerException
- * if any parameter is null
- */
- public Builder(String uri, String resourceType,
- String resourceInterface) {
- if (uri == null) {
- throw new NullPointerException("uri is null.");
- }
- if (resourceType == null) {
- throw new NullPointerException("resourceType is null.");
- }
- if (resourceInterface == null) {
- throw new NullPointerException("resourceInterface is null.");
- }
-
- mUri = uri;
- mType = resourceType;
- mInterface = resourceInterface;
- }
-
- /**
- * Sets whether the resource is discoverable.
- *
- * @param isDiscoverable
- * whether to be discoverable or not
- *
- */
- public Builder setDiscoverable(boolean isDiscoverable) {
- mIsDiscovervable = isDiscoverable;
- return this;
- }
-
- /**
- * Sets the observable(OC_OBSERVABLE) property of the resource.
- *
- * @param isObservable
- * whether to be observable or not
- *
- */
- public Builder setObservable(boolean isObservable) {
- mIsObservable = isObservable;
- return this;
- }
-
- /**
- * Sets attributes foe the resource.
- *
- */
- public Builder setAttributes(RcsResourceAttributes attributes) {
- mAttributes = attributes;
- return this;
- }
-
- /**
- * Register a resource and returns a RCSResourceObject.
- *
- * @throws RcsPlatformException
- * If registering a resource is failed.
- *
- */
- public RcsResourceObject build() {
- return nativeBuild(mUri, mType, mInterface, mIsObservable,
- mIsDiscovervable, mAttributes);
- }
- }
-
- /**
- * This provides the way to get the attributes of RcsResourceObject with
- * lock.
- * When a thread holds the lock, the other threads will be pending until the
- * lock is released by unlock.
- *
- * Here is the standard idiom for AttributesLock:
- *
- * <pre>
- * {@code
- * AttributesLock lock = rcsResourceObject.getAttributesLock();
- *
- * try {
- * lock.lock();
- *
- * ....
- *
- * lock.apply();
- * } finally {
- * lock.unlock();
- * }
- * }
- * </pre>
- */
- public static class AttributesLock {
-
- private final WeakReference<RcsResourceObject> mResourceObjectRef;
-
- private RcsLockedAttributes mCurrentAttributes;
-
- private AttributesLock(RcsResourceObject resourceObj) {
- mResourceObjectRef = new WeakReference<RcsResourceObject>(
- resourceObj);
- }
-
- private RcsResourceObject ensureResourceObject() throws RcsException {
- final RcsResourceObject object = mResourceObjectRef.get();
-
- if (object == null || object.isDestroyed()) {
- throw new RcsDestroyedObjectException(
- "The object is already destroyed!");
- }
-
- return object;
- }
-
- /**
- * Locks the attributes of the RcsResourceObject and returns locked
- * attributes that can be modified until unlocked.
- *
- * @return Locked attributes.
- *
- * @throws RcsException
- * if the RcsResourceObject is destroyed
- */
- public RcsLockedAttributes lock() throws RcsException {
- return mCurrentAttributes = new RcsLockedAttributes(
- ensureResourceObject());
- }
-
- /**
- * Changes the state to unlock of the attributes of the
- * RcsResourceObject.
- *
- */
- public void unlock() {
- if (mCurrentAttributes == null) return;
-
- mCurrentAttributes.setUnlockState();
- mCurrentAttributes = null;
- }
-
- /**
- * Applies the modified attributes to the RcsResourceObject.
- *
- * @throws RcsIllegalStateException
- * if not in locked state
- * @throws RcsPlatformException
- * if auto notify failed
- */
- public void apply() throws RcsIllegalStateException {
- if (mCurrentAttributes == null) {
- throw new RcsIllegalStateException("it is not locked state.");
- }
- mCurrentAttributes.apply();
- }
- }
-
- private static native RcsResourceObject nativeBuild(String uri,
- String resourceType, String resourceInterface, boolean isObservable,
- boolean isDiscoverable, RcsResourceAttributes attributes);
-
- private native void nativeSetAttribute(String key, RcsValue value);
-
- private native RcsValue nativeGetAttributeValue(String key);
-
- private native boolean nativeRemoveAttribute(String key);
-
- private native boolean nativeContainsAttribute(String key);
-
- private native RcsResourceAttributes nativeGetAttributes();
-
- private native boolean nativeIsObservable();
-
- private native boolean nativeIsDiscoverable();
-
- private native void nativeNotify();
-
- private native void nativeSetAutoNotifyPolicy(AutoNotifyPolicy policy);
-
- private native AutoNotifyPolicy nativeGetAutoNotifyPolicy();
-
- private native void nativeSetSetRequestHandlerPolicy(
- SetRequestHandlerPolicy policy);
-
- private native SetRequestHandlerPolicy nativeGetSetRequestHandlerPolicy();
-
- private native void nativeSetGetRequestHandler(GetRequestHandler handler);
-
- private native void nativeSetSetRequestHandler(SetRequestHandler handler);
-
- private native void nativeAddAttributeUpdatedListener(String key,
- OnAttributeUpdatedListener listener);
-
- private native boolean nativeRemoveAttributeUpdatedListener(String key);
-
- private RcsResourceObject() {
- }
-
- /**
- * Represents the policy of AutoNotify function of RCSResourceObject class
- * In accord with this, observers are notified of attributes that are
- * changed or updated.
- *
- * <p>
- * Attributes are changed or updated according to execution of some
- * functions which modify attributes or receipt of set requests.
- *
- * @see setAttribute
- * @see removeAttribute
- * @see getAttributesLock
- *
- */
- public enum AutoNotifyPolicy {
- /** Never */
- NEVER,
-
- /** Always */
- ALWAYS,
-
- /** When attributes are changed */
- UPDATED
- }
-
- /**
- * Represents the policy of set-request handler.
- * In accord with this, the RCSResourceObject decides whether a set-request
- * is
- * acceptable or not.
- */
- public enum SetRequestHandlerPolicy {
- /**
- * Requests will be ignored if attributes of the request contain
- * a new key or a value that has different type from the current
- * value of the key.
- */
- NEVER,
-
- /**
- * The attributes of the request will be applied unconditionally
- * even if there are new name or type conflicts.
- */
- ACCEPT
- }
-
- /**
- * Interface definition for a handler to be invoked when a get request is
- * received.
- * <p>
- * The handler will be called first when a get request is received, before
- * the RCSResourceObject handles.
- *
- * @see setGetRequestHandler
- */
- public interface GetRequestHandler {
-
- /**
- * Called when received a get request from the client.
- *
- * @param request
- * Request information.
- * @param attributes
- * The attributes of the request.
- *
- * @return A response to be sent.
- *
- * @see RcsGetResponse
- */
- RcsGetResponse onGetRequested(RcsRequest request,
- RcsResourceAttributes attributes);
-
- }
-
- /**
- * Interface definition for a handler to be invoked when a set request is
- * received.
- * <p>
- * The handler will be called first when a get request is received, before
- * the RCSResourceObject handles. If the attributes are modified in the
- * callback, the modified attributes will be set in the RCSResourceObject if
- * the request is not ignored.
- *
- * @see setGetRequestHandler
- */
- public interface SetRequestHandler {
-
- /**
- * Called when received a set request from the client.
- *
- * @param request
- * request information
- * @param attributes
- * the attributes of the request.
- * it will be applied to the RcsResourceObject
- *
- * @return A response indicating how to handle this request.
- *
- * @see RcsSetResponse
- */
- RcsSetResponse onSetRequested(RcsRequest request,
- RcsResourceAttributes attributes);
-
- }
-
- /**
- * Interface definition for a callback to be invoked when an attribute is
- * updated.
- */
- public interface OnAttributeUpdatedListener {
-
- /**
- * Called when an attribute value is updated.
- *
- * @param oldValue
- * the attribute value before updated
- * @param newValue
- * the current resource attribute value
- */
- void onAttributeUpdated(RcsValue oldValue, RcsValue newValue);
- }
-
- private void assertAlive() throws RcsException {
- if (!hasHandle()) {
- throw new RcsDestroyedObjectException(
- "The object is already destroyed!");
- }
- }
-
- /**
- * Sets a particular attribute value.
- *
- * @param key
- * key with which the specified value is to be associated
- * @param value
- * value to be associated with the specified key
- *
- * @throws RcsDestroyedObjectException
- * if the object is destroyed
- * @throws NullPointerException
- * if key or value is null
- *
- */
- public void setAttribute(String key, RcsValue value) throws RcsException {
- assertAlive();
-
- if (key == null) throw new NullPointerException("key is null");
- if (value == null) throw new NullPointerException("value is null");
-
- nativeSetAttribute(key, value);
- }
-
- /**
- * Returns a copied attribute value associated with the supplied key.
- *
- * @param key
- * the key whose associated value is to be returned
- *
- * @return the value to which the specified key is mapped, or null if no
- * attribute for the key
- *
- * @throws RcsDestroyedObjectException
- * if the object is destroyed
- * @throws NullPointerException
- * if key is null
- */
- public RcsValue getAttributeValue(String key) throws RcsException {
- assertAlive();
-
- if (key == null) throw new NullPointerException("key is null");
- return nativeGetAttributeValue(key);
- }
-
- /**
- * Removes the mapping for a key from the attributes if it is present.
- *
- * @param key
- * key whose mapping is to be removed
- *
- * @return true if the key is present and the the value mapped is removed.
- *
- * @throws RcsDestroyedObjectException
- * if the object is destroyed
- * @throws NullPointerException
- * if key is null
- */
- public boolean removeAttribute(String key) throws RcsException {
- assertAlive();
-
- if (key == null) throw new NullPointerException("key is null");
- return nativeRemoveAttribute(key);
- }
-
- /**
- * Returns true if the attributes contains a mapping for the specified key.
- *
- * @param key
- * key whose presence is to be tested
- *
- * @return true if the attributes contains a mapping for the specified key.
- *
- * @throws RcsDestroyedObjectException
- * if the object is destroyed
- * @throws NullPointerException
- * if key is null
- */
- public boolean containsAttribute(String key) throws RcsException {
- assertAlive();
-
- if (key == null) throw new NullPointerException("key is null");
- return nativeContainsAttribute(key);
- }
-
- /**
- * Returns a copied attributes of the RCSResourceObject.
- * To modify the attributes, use {@link AttributesLock}.
- *
- * @throws RcsDestroyedObjectException
- * if the object is destroyed
- *
- * @see getAttributesLock
- */
- public RcsResourceAttributes getAttributes() throws RcsException {
- assertAlive();
-
- return nativeGetAttributes();
- }
-
- /**
- * Returns an AttributesLock for this RcsResourceObject.
- *
- * @throws RcsDestroyedObjectException
- * if the object is destroyed
- */
- public AttributesLock getAttributesLock() throws RcsException {
- assertAlive();
-
- return new AttributesLock(this);
- }
-
- /**
- * Checks whether the resource is observable or not.
- *
- * @throws RcsDestroyedObjectException
- * if the object is destroyed
- */
- public boolean isObservable() throws RcsException {
- assertAlive();
-
- return nativeIsObservable();
- }
-
- /**
- * Checks whether the resource is discoverable or not.
- *
- * @throws RcsDestroyedObjectException
- * if the object is destroyed
- */
- public boolean isDiscoverable() throws RcsException {
- assertAlive();
-
- return nativeIsDiscoverable();
- }
-
- /**
- * Sets the get request handler. To remove handler, pass null.
- *
- * Default behavior is {@link RcsGetResponse#defaultAction()}.
- *
- * @throws RcsDestroyedObjectException
- * if the object is destroyed
- */
- public void setGetRequestHandler(GetRequestHandler handler)
- throws RcsException {
- assertAlive();
-
- nativeSetGetRequestHandler(handler);
- }
-
- /**
- * Sets the set request handler. To remove handler, pass null.
- *
- * Default behavior is {@link RcsSetResponse#defaultAction()}.
- *
- * @throws RcsDestroyedObjectException
- * if the object is destroyed
- *
- */
- public void setSetRequestHandler(SetRequestHandler handler)
- throws RcsException {
- assertAlive();
-
- nativeSetSetRequestHandler(handler);
- }
-
- /**
- * Adds a listener for a particular attribute updated.
- *
- * @param key
- * the interested attribute's key
- * @param listener
- * listener to be invoked
- *
- * @throws NullPointerException
- * if key or listener is null
- * @throws RcsDestroyedObjectException
- * if the object is destroyed
- */
- public void addAttributeUpdatedListener(String key,
- OnAttributeUpdatedListener listener) throws RcsException {
- assertAlive();
-
- if (key == null) {
- throw new NullPointerException("key is null.");
- }
- if (listener == null) {
- throw new NullPointerException("listener is null.");
- }
-
- nativeAddAttributeUpdatedListener(key, listener);
- }
-
- /**
- * Removes a listener for a particular attribute updated.
- *
- * @param key
- * key the key associated with the listener to be removed
- *
- * @return true if the listener added with same key exists and is removed.
- *
- * @throws RcsDestroyedObjectException
- * if the object is destroyed
- * @throws NullPointerException
- * if key is null
- */
- public boolean removeAttributeUpdatedListener(String key)
- throws RcsException {
- assertAlive();
-
- if (key == null) throw new NullPointerException("key is null");
- return nativeRemoveAttributeUpdatedListener(key);
- }
-
- /**
- * Notifies all observers of the current attributes.
- *
- * @throws RcsDestroyedObjectException
- * if the object is destroyed
- * @throws RcsPlatformException
- * if the operation failed
- */
- public void notifyObservers() throws RcsException {
- assertAlive();
-
- nativeNotify();
- }
-
- /**
- * Sets auto notify policy
- *
- * @param policy
- * policy to be set
- *
- * @throws RcsDestroyedObjectException
- * if the object is destroyed
- *
- */
- public void setAutoNotifyPolicy(AutoNotifyPolicy policy)
- throws RcsException {
- assertAlive();
-
- if (policy == null) throw new NullPointerException("policy is null");
- nativeSetAutoNotifyPolicy(policy);
- }
-
- /**
- * Returns the current policy
- *
- * @throws RcsDestroyedObjectException
- * if the object is destroyed
- *
- */
- public AutoNotifyPolicy getAutoNotifyPolicy() throws RcsException {
- assertAlive();
-
- return nativeGetAutoNotifyPolicy();
- }
-
- /**
- * Sets the policy for handling a set request.
- *
- * @param policy
- * policy to be set
- *
- * @throws RcsDestroyedObjectException
- * if the object is destroyed
- *
- */
- public void setSetRequestHandlerPolicy(SetRequestHandlerPolicy policy)
- throws RcsException {
- assertAlive();
-
- if (policy == null) throw new NullPointerException("policy is null");
- nativeSetSetRequestHandlerPolicy(policy);
- }
-
- /**
- * Returns the current policy.
- *
- * @throws RcsDestroyedObjectException
- * if the object is destroyed
- */
- public SetRequestHandlerPolicy getSetRequestHandlerPolicy()
- throws RcsException {
- assertAlive();
-
- return nativeGetSetRequestHandlerPolicy();
- }
-
- private boolean isDestroyed() {
- return !hasHandle();
- }
-
- /**
- * Unregister the resource and reclaims all resources used by this object.
- * This must be called if the resource is not used any longer.
- *
- */
- public void destroy() {
- super.dispose();
- }
-}
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-package org.iotivity.service.server;
-
-import org.iotivity.service.RcsResourceAttributes;
-
-class RcsResponse {
- private native static int nativeGetDefaultErrorCode();
-
- public static final int DEFAULT_ERROR_CODE;
-
- static {
- DEFAULT_ERROR_CODE = nativeGetDefaultErrorCode();
- }
-
- private final int mErrorCode;
- private final RcsResourceAttributes mAttrs;
-
- RcsResponse() {
- this(DEFAULT_ERROR_CODE);
- }
-
- RcsResponse(RcsResourceAttributes attrs) {
- this(attrs, DEFAULT_ERROR_CODE);
- }
-
- RcsResponse(int errorCode) {
- this(null, errorCode);
- }
-
- RcsResponse(RcsResourceAttributes attrs, int errorCode) {
- mErrorCode = errorCode;
- mAttrs = attrs;
- }
-}
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-package org.iotivity.service.server;
-
-import org.iotivity.service.RcsResourceAttributes;
-
-/**
- * This class provides methods to create the response for a received set
- * request.
- *
- * @see RcsResourceObject
- * @see RcsSetResponse
- */
-public final class RcsSetResponse extends RcsResponse {
- /**
- * Options for handling a set request.
- *
- * This overrides {@link RcsResourceObject.SetRequestHandlerPolicy}.
- *
- */
- public enum AcceptanceMethod {
- /**
- * Follow {@link RcsResourceObject.SetRequestHandlerPolicy}.
- */
- DEFAULT,
-
- /**
- * Accept the request attributes even if there is an unknown key or
- * mismatched type.
- */
- ACCEPT,
-
- /**
- * Ignore the request attributes.
- */
- IGNORE
- };
-
- private AcceptanceMethod mAcceptanceMethod = AcceptanceMethod.DEFAULT;
-
- /**
- * Creates a default RcsSetResponse with {@link AcceptanceMethod#DEFAULT}.
- * The response will have {@link #DEFAULT_ERROR_CODE} for the errorCode. The
- * attributes of {@link RcsResourceObject} will be set as the result
- * attributes.
- *
- */
- public static RcsSetResponse defaultAction() {
- return new RcsSetResponse();
- }
-
- /**
- * Creates a default RcsSetResponse with {@link AcceptanceMethod#ACCEPT}
- * The response will have {@link #DEFAULT_ERROR_CODE} for the errorCode. The
- * attributes of {@link RcsResourceObject} will be set as the result
- * attributes.
- *
- */
- public static RcsSetResponse accept() {
- return new RcsSetResponse()
- .setAcceptanceMethod(AcceptanceMethod.ACCEPT);
- }
-
- /**
- * Creates a RcsSetResponse with {@link AcceptanceMethod#ACCEPT} and error
- * code passed.
- * The attributes of the {@link RcsResourceObject} will be set as the result
- * attributes.
- *
- * @param errorCode
- * error code to be set in response
- *
- */
- public static RcsSetResponse accept(int errorCode) {
- return new RcsSetResponse(errorCode)
- .setAcceptanceMethod(AcceptanceMethod.ACCEPT);
- }
-
- /**
- * Creates a default RcsSetResponse with {@link AcceptanceMethod#IGNORE}.
- * The response will have {@link #DEFAULT_ERROR_CODE} for the errorCode. The
- * attributes of {@link RcsResourceObject} will be set as the result
- * attributes.
- *
- */
- public static RcsSetResponse ignore() {
- return new RcsSetResponse()
- .setAcceptanceMethod(AcceptanceMethod.IGNORE);
- }
-
- /**
- * Creates a RcsSetResponse with {@link AcceptanceMethod#IGNORE} and error
- * code passed. The attributes of the {@link RcsResourceObject} will be set
- * as the result attributes.
- *
- * @param errorCode
- * error code to be set in response
- *
- */
- public static RcsSetResponse ignore(int errorCode) {
- return new RcsSetResponse(errorCode)
- .setAcceptanceMethod(AcceptanceMethod.IGNORE);
- }
-
- /**
- * Creates a RcsSetResponse with error code passed and
- * {@link AcceptanceMethod#DEFAULT}. The attributes of the
- * {@link RcsResourceObject} will be set as the result attributes.
- *
- * @param errorCode
- * error code to be set in response
- *
- */
- public static RcsSetResponse create(int errorCode) {
- return new RcsSetResponse(errorCode);
- }
-
- /**
- * Creates a RcsSetResponse with custom attributes and
- * {@link AcceptanceMethod#DEFAULT}. This sends the passed attributes as the
- * result attributes instead of one the {@link RcsResourceObject} holds.
- *
- * @param attributes
- * attributes to be sent as the result
- *
- */
- public static RcsSetResponse create(RcsResourceAttributes attributes) {
- return new RcsSetResponse(attributes);
- }
-
- /**
- * Creates a RcsSetResponse with error code passed and
- * {@link AcceptanceMethod#DEFAULT}. This sends the passed attributes as the
- * result attributes instead of one the {@link RcsResourceObject} holds.
- *
- * @param attributes
- * attributes to be sent as the result
- * @param errorCode
- * error code for response
- *
- */
- public static RcsSetResponse create(RcsResourceAttributes attributes,
- int errorCode) {
- return new RcsSetResponse(attributes, errorCode);
- }
-
- /**
- * Returns the acceptance method.
- *
- */
- public AcceptanceMethod getAcceptanceMethod() {
- return mAcceptanceMethod;
- }
-
- /**
- * Sets the acceptance method.
- *
- * @param method
- * method to be set
- *
- * @return The reference to this RcsSetResponse
- *
- */
- public RcsSetResponse setAcceptanceMethod(AcceptanceMethod method) {
- mAcceptanceMethod = method;
- return this;
- }
-
- private RcsSetResponse() {
- super();
- }
-
- private RcsSetResponse(int errorCode) {
- super(errorCode);
- }
-
- private RcsSetResponse(RcsResourceAttributes attrs) {
- super(attrs);
- }
-
- private RcsSetResponse(RcsResourceAttributes attrs, int errorCode) {
- super(attrs, errorCode);
- }
-
-}
+++ /dev/null
-package org.iotivity.service.server;
-
-import org.iotivity.service.RcsException;
-
-/**
- * Thrown when trying to access a unlocked {@link RcsLockedAttributes}.
- *
- */
-public class RcsUnlockedException extends RcsException {
-
- private static final long serialVersionUID = 4292243643497860992L;
-
- public RcsUnlockedException(String message) {
- super(message);
- }
-
-}
+++ /dev/null
-LOCAL_PATH := $(call my-dir)
-
-ROOT_PATH := ../../../../../../..
-IOTIVITY_LIB_PATH := $(ROOT_PATH)/out/android/$(TARGET_ARCH_ABI)/$(APP_OPTIM)
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := rcs_common
-LOCAL_SRC_FILES := $(IOTIVITY_LIB_PATH)/librcs_common.so
-include $(PREBUILT_SHARED_LIBRARY)
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := rcs_client
-LOCAL_SRC_FILES := $(IOTIVITY_LIB_PATH)/librcs_client.so
-include $(PREBUILT_SHARED_LIBRARY)
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := rcs_server
-LOCAL_SRC_FILES := $(IOTIVITY_LIB_PATH)/librcs_server.so
-include $(PREBUILT_SHARED_LIBRARY)
-
-include $(CLEAR_VARS)
-OIC_SRC_DIR := ../../../../../..
-LOCAL_MODULE := rcs_jni
-
-LOCAL_C_INCLUDES := $(LOCAL_PATH)/util
-LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/resource/include
-LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/resource/c_common
-LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/resource/csdk/stack/include
-LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/extlibs/boost/boost_1_58_0
-LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/service/resource-encapsulation/include
-LOCAL_C_INCLUDES += $(OIC_SRC_DIR)/service/resource-encapsulation/src/serverBuilder/include
-
-LOCAL_SRC_FILES += $(patsubst $(LOCAL_PATH)/%, %, $(wildcard $(LOCAL_PATH)/util/*.cpp))
-LOCAL_SRC_FILES += $(patsubst $(LOCAL_PATH)/%, %, $(wildcard $(LOCAL_PATH)/*.cpp))
-
-LOCAL_CPPFLAGS := -std=c++0x -frtti -fexceptions
-
-LOCAL_LDLIBS := -llog
-
-LOCAL_SHARED_LIBRARIES += rcs_common
-LOCAL_SHARED_LIBRARIES += rcs_client
-LOCAL_SHARED_LIBRARIES += rcs_server
-
-include $(BUILD_SHARED_LIBRARY)
+++ /dev/null
-NDK_TOOLCHAIN_VERSION := 4.9
-APP_STL := gnustl_shared
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-#include "JniRcsDiscoveryManager.h"
-#include "JniRcsObject.h"
-#include "JniRcsRemoteResourceObject.h"
-#include "JniRcsResourceAttributes.h"
-#include "JniRcsResourceObject.h"
-#include "JniRcsValue.h"
-#include "JavaClasses.h"
-#include "JavaExceptions.h"
-#include "JNIEnvWrapper.h"
-#include "Log.h"
-
-#define LOG_TAG "JNI-Main"
-
-#define JNI_CURRENT_VERSION JNI_VERSION_1_6
-
-JavaVM *g_jvm;
-
-JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved)
-{
- LOGI("JNI_OnLoad");
- JNIEnv *env;
- g_jvm = vm;
-
- if (g_jvm->GetEnv((void **)&env, JNI_CURRENT_VERSION) != JNI_OK)
- {
- LOGE("Failed to get the environment using GetEnv()");
- return JNI_ERR;
- }
-
- JNIEnvWrapper envWrapper{ env };
-
- try
- {
- initJavaClasses(&envWrapper);
- initJavaExceptions(&envWrapper);
- initRCSValue(&envWrapper);
- initRCSResourceAttributes(&envWrapper);
- initRCSDiscoveryManager(&envWrapper);
- initRCSRemoteResourceObject(&envWrapper);
- initRCSObject(&envWrapper);
- initRCSResourceObject(&envWrapper);
- }
- catch (const JavaException&)
- {
- if (env->ExceptionCheck()) env->ExceptionDescribe();
- return JNI_ERR;
- }
-
- return JNI_CURRENT_VERSION;
-}
-
-JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *vm, void *reserved)
-{
- LOGI("JNI_OnUnload");
- JNIEnv *env;
-
- if (g_jvm->GetEnv((void **)&env, JNI_CURRENT_VERSION) != JNI_OK)
- {
- LOGE("Failed to get the environment using GetEnv()");
- return;
- }
-
- JNIEnvWrapper envWrapper{ env };
-
- try
- {
- clearRCSResourceObject(&envWrapper);
- clearRCSObject(&envWrapper);
- clearRCSRemoteResourceObject(&envWrapper);
- clearRCSDiscoveryManager(&envWrapper);
- clearRCSResourceAttributes(&envWrapper);
- clearRCSValue(&envWrapper);
- clearJavaExceptions(&envWrapper);
- clearJavaClasses(&envWrapper);
- }
- catch (const JavaException&)
- {
- }
-}
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-#include "JniRcsDiscoveryManager.h"
-
-#include "JniRcsObject.h"
-#include "JniRcsRemoteResourceObject.h"
-#include "JavaClasses.h"
-#include "JavaExceptions.h"
-#include "JavaGlobalRef.h"
-#include "JNIEnvWrapper.h"
-#include "Log.h"
-#include "ScopedEnv.h"
-#include "Verify.h"
-
-#include "RCSDiscoveryManager.h"
-#include "RCSAddress.h"
-#include "RCSRemoteResourceObject.h"
-
-using namespace OIC::Service;
-
-#define LOG_TAG "JNI-DiscoveryManager"
-
-#define CLS_NAME_DISCOVERY_MANAGER PACKAGE_NAME "/client/RcsDiscoveryManager"
-
-#define CLS_NAME_ON_RESOURCE_DISCOVERED_LISTENER \
- CLS_NAME_DISCOVERY_MANAGER "$OnResourceDiscoveredListener"
-
-#define CLS_NAME_DISCOVERY_TASK CLS_NAME_DISCOVERY_MANAGER "$DiscoveryTask"
-
-namespace
-{
- jclass g_cls_DiscoveryaTask;
-
- jmethodID g_method_onResourceDiscovered;
-
- jmethodID g_ctor_DiscoveryTask;
-}
-
-void initRCSDiscoveryManager(JNIEnvWrapper* env)
-{
- auto clsOnResourceDiscoveredListener = env->FindClass(CLS_NAME_ON_RESOURCE_DISCOVERED_LISTENER);
-
- g_method_onResourceDiscovered = env->GetMethodID(clsOnResourceDiscoveredListener,
- "onResourceDiscovered", "(" AS_SIG(CLS_NAME_REMOTERESOURCEOBJECT) ")V");
-
- g_cls_DiscoveryaTask = env->FindClassAsGlobalRef(CLS_NAME_DISCOVERY_TASK);
-
- g_ctor_DiscoveryTask = env->GetConstructorID(g_cls_DiscoveryaTask, "()V");
-}
-
-void clearRCSDiscoveryManager(JNIEnvWrapper* env)
-{
- env->DeleteGlobalRef(g_cls_DiscoveryaTask);
-}
-
-void onResourceDiscovered(RCSRemoteResourceObject::Ptr resource, const JavaGlobalRef& listener)
-{
- LOGI("onResourceDiscovered");
-
- ScopedEnvWrapper env;
- EXPECT(env, "env is null!");
-
- try
- {
- auto newResourceObj = newRemoteResourceObject(env.get());
-
- setSafeNativeHandle< RCSRemoteResourceObject::Ptr >(env.get(),
- newResourceObj, std::move(resource));
-
- env->CallVoidMethod(listener, g_method_onResourceDiscovered, newResourceObj);
- }
- catch (const JavaException&)
- {
- env->ExceptionDescribe();
- env->ExceptionClear();
- }
-}
-
-JNIEXPORT jobject JNICALL
-Java_org_iotivity_service_client_RcsDiscoveryManager_nativeDiscoverResource(
- JNIEnv *env, jclass obj, jstring address, jstring uri, jstring resourceType,
- jobject listener)
-{
- LOGI("discoverResource");
-
- RCSAddress rcsAddress{ address ? RCSAddress::unicast(toStdString(env, address)) :
- RCSAddress::multicast() };
-
- try
- {
- auto discoveryTask = RCSDiscoveryManager::getInstance()->discoverResourceByType(
- std::move(rcsAddress), toStdString(env, uri), toStdString(env, resourceType),
- std::bind(onResourceDiscovered, std::placeholders::_1, JavaGlobalRef{ env, listener }));
-
- auto taskObj = env->NewObject(g_cls_DiscoveryaTask, g_ctor_DiscoveryTask);
- VERIFY_NO_EXC_RET_DEF(env);
-
- setSafeNativeHandle< decltype(discoveryTask) >(env, taskObj, std::move(discoveryTask));
-
- return taskObj;
- }
- catch (const RCSPlatformException& e) {
- throwPlatformException(env, e);
- }
-
- return nullptr;
-}
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-#ifndef JNI_RCS_DISCOVERY_MANAGER_H_
-#define JNI_RCS_DISCOVERY_MANAGER_H_
-
-#include <jni.h>
-
-class JNIEnvWrapper;
-
-void initRCSDiscoveryManager(JNIEnvWrapper*);
-void clearRCSDiscoveryManager(JNIEnvWrapper*);
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-JNIEXPORT jobject JNICALL
-Java_org_iotivity_service_client_RcsDiscoveryManager_nativeDiscoverResource
-(JNIEnv*, jclass, jstring address, jstring relativeURI, jstring resourceType, jobject listener);
-
-#ifdef __cplusplus
-}
-#endif
-#endif //JNI_RCS_DISCOVERY_MANAGER_H_
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-#include "JniRcsLockedAttributes.h"
-
-#include "JniRcsObject.h"
-#include "JniRcsResourceAttributes.h"
-#include "JniRcsValue.h"
-#include "Log.h"
-#include "Verify.h"
-#include "JavaExceptions.h"
-
-#include "RCSResourceObject.h"
-
-#define LOG_TAG "JNI-RCSLockedAttributes"
-
-using namespace OIC::Service;
-
-namespace
-{
- inline RCSResourceObject::Ptr& getResource(JNIEnv* env, jobject obj)
- {
- return getNativeHandleAs< RCSResourceObject::Ptr >(env, obj);
- }
-}
-
-// The prerequisite for below methods is for ResourceObject's attributes being locked.
-// This is guaranteed by class named RCSResourceObject.AttributesLock on Java layer.
-
-JNIEXPORT jboolean JNICALL
-Java_org_iotivity_service_server_RcsLockedAttributes_nativeIsEmpty
-(JNIEnv* env, jclass, jobject resourceObject)
-{
- auto res = getResource(env, resourceObject);
- VERIFY_NO_EXC_RET_DEF(env);
-
- return res->getAttributes().empty();
-}
-
-JNIEXPORT jint JNICALL
-Java_org_iotivity_service_server_RcsLockedAttributes_nativeSize
-(JNIEnv* env, jclass, jobject resourceObject)
-{
- auto res = getResource(env, resourceObject);
- VERIFY_NO_EXC_RET_DEF(env);
-
- return res->getAttributes().size();
-}
-
-JNIEXPORT jboolean JNICALL
-Java_org_iotivity_service_server_RcsLockedAttributes_nativeRemove
-(JNIEnv* env, jclass, jobject resourceObject, jstring keyObj)
-{
- EXPECT_RET_DEF(keyObj, "keyObj is null");
-
- auto res = getResource(env, resourceObject);
- VERIFY_NO_EXC_RET_DEF(env);
-
- auto key = toStdString(env, keyObj);
- VERIFY_NO_EXC_RET_DEF(env);
-
- return res->getAttributes().erase(key);
-}
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_server_RcsLockedAttributes_nativeClear
-(JNIEnv* env, jclass, jobject resourceObject)
-{
- auto res = getResource(env, resourceObject);
- VERIFY_NO_EXC(env);
-
- res->getAttributes().clear();
-}
-
-JNIEXPORT jboolean JNICALL
-Java_org_iotivity_service_server_RcsLockedAttributes_nativeContains
-(JNIEnv* env, jclass, jobject resourceObject, jstring keyObj)
-{
- EXPECT_RET_DEF(keyObj, "keyObj is null");
-
- auto res = getResource(env, resourceObject);
- VERIFY_NO_EXC_RET_DEF(env);
-
- auto key = toStdString(env, keyObj);
- VERIFY_NO_EXC_RET_DEF(env);
-
- return res->getAttributes().contains(key);
-}
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_server_RcsLockedAttributes_nativeAddKeys
-(JNIEnv* env, jclass, jobject resourceObject, jstring setObj)
-{
- EXPECT(setObj, "set is null.");
-
- auto res = getResource(env, resourceObject);
- VERIFY_NO_EXC(env);
-
- for (const auto& keyValue : res->getAttributes())
- {
- JavaLocalString localObj{ env, env->NewStringUTF(keyValue.key().c_str()) };
- VERIFY_NO_EXC(env);
-
- invoke_Collection_add(env, setObj, localObj);
- VERIFY_NO_EXC(env);
- }
-}
-
-JNIEXPORT jobject JNICALL
-Java_org_iotivity_service_server_RcsLockedAttributes_nativeAsJavaObject
-(JNIEnv* env, jclass, jobject resourceObject, jstring keyObj)
-{
- EXPECT_RET_DEF(keyObj, "Key is null.");
-
- auto res = getResource(env, resourceObject);
- VERIFY_NO_EXC_RET_DEF(env);
-
- auto key = toStdString(env, keyObj);
- VERIFY_NO_EXC_RET_DEF(env);
-
- auto& attrs = res->getAttributes();
-
- EXPECT_RET_DEF(attrs.contains(key), "no matched value");
-
- jobject valueObj = newRCSValueObject(env, attrs[key]);
- VERIFY_NO_EXC_RET_DEF(env);
-
- return valueObj;
-}
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_server_RcsLockedAttributes_nativeApply
-(JNIEnv* env, jclass, jobject resourceObject, jstring cacheObj)
-{
- EXPECT(cacheObj, "cacheObj is null.");
-
- auto res = getResource(env, resourceObject);
- VERIFY_NO_EXC(env);
-
- try
- {
- RCSResourceObject::LockGuard lock(res);
- writeNativeAttributesFromMap(env, cacheObj, res->getAttributes());
- }
- catch (const RCSPlatformException& e)
- {
- throwPlatformException(env, e);
- }
-}
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_server_RcsLockedAttributes_nativeLock
-(JNIEnv* env, jobject obj, jobject resourceObject)
-{
- auto res = getResource(env, resourceObject);
- VERIFY_NO_EXC(env);
-
- setSafeNativeHandle< RCSResourceObject::LockGuard >(env, obj,
- res, RCSResourceObject::AutoNotifyPolicy::NEVER);
-}
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_server_RcsLockedAttributes_nativeUnlock(JNIEnv* env, jobject obj)
-{
- releaseNativeHandle(env, obj);
-}
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-#ifndef JNI_RCS_LOCKED_ATTRIBUTES_H_
-#define JNI_RCS_LOCKED_ATTRIBUTES_H_
-
-#include <jni.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-JNIEXPORT jboolean JNICALL
-Java_org_iotivity_service_server_RcsLockedAttributes_nativeIsEmpty
-(JNIEnv*, jclass, jobject);
-
-JNIEXPORT jint JNICALL
-Java_org_iotivity_service_server_RcsLockedAttributes_nativeSize
-(JNIEnv*, jclass, jobject);
-
-JNIEXPORT jboolean JNICALL
-Java_org_iotivity_service_server_RcsLockedAttributes_nativeRemove
-(JNIEnv*, jclass, jobject, jstring keyObj);
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_server_RcsLockedAttributes_nativeClear
-(JNIEnv*, jclass, jobject);
-
-JNIEXPORT jboolean JNICALL
-Java_org_iotivity_service_server_RcsLockedAttributes_nativeContains
-(JNIEnv*, jclass, jobject, jstring keyObj);
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_server_RcsLockedAttributes_nativeAddKeys
-(JNIEnv*, jclass, jobject, jstring setObj);
-
-JNIEXPORT jobject JNICALL
-Java_org_iotivity_service_server_RcsLockedAttributes_nativeAsJavaObject
-(JNIEnv*, jclass, jobject, jstring keyObj);
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_server_RcsLockedAttributes_nativeApply
-(JNIEnv*, jclass, jobject, jstring cacheObj);
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_server_RcsLockedAttributes_nativeLock
-(JNIEnv*, jobject, jobject);
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_server_RcsLockedAttributes_nativeUnlock
-(JNIEnv*, jobject);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif //JNI_RCS_LOCKED_ATTRIBUTES_H_
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-#include "JniRcsObject.h"
-
-#include "JavaClasses.h"
-#include "JNIEnvWrapper.h"
-#include "Log.h"
-#include "Verify.h"
-
-#define LOG_TAG "JNI-RCSObject"
-
-jfieldID g_field_mNativeHandle;
-
-void initRCSObject(JNIEnvWrapper* env)
-{
- auto clsRCSObject = env->FindClass(PACKAGE_NAME "/RcsObject");
-
- g_field_mNativeHandle = env->GetFieldID(clsRCSObject, "mNativeHandle", "J");
-}
-
-void clearRCSObject(JNIEnvWrapper* env)
-{
-}
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_RcsObject_nativeDispose(JNIEnv* env, jobject obj)
-{
- LOGD("release nativeHandle!");
- releaseNativeHandle(env, obj);
-}
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-#ifndef JNI_RCS_OBJECT_H_
-#define JNI_RCS_OBJECT_H_
-
-#include <jni.h>
-
-#include <memory>
-
-#include "JavaClasses.h"
-#include "JNIEnvWrapper.h"
-
-extern jfieldID g_field_mNativeHandle;
-
-void initRCSObject(JNIEnvWrapper*);
-void clearRCSObject(JNIEnvWrapper*);
-
-namespace Detail
-{
- struct BaseHandleHolder
- {
- virtual ~BaseHandleHolder() {}
- };
-
- template< typename T >
- struct HandleHolder: public BaseHandleHolder
- {
- HandleHolder(T* ptr) : m_ptr { ptr } {}
-
- virtual ~HandleHolder() { delete m_ptr; }
-
- T* m_ptr;
- };
-
- template< typename ENV >
- void* getNativeHandle(ENV* env, jobject obj)
- {
- return reinterpret_cast< void* >(env->GetLongField(obj, g_field_mNativeHandle));
- }
-}
-
-template< typename ENV >
-bool hasNativeHandle(ENV* env, jobject obj)
-{
- return Detail::getNativeHandle(env, obj) != nullptr;
-}
-
-template< typename T, typename ENV, typename ...PARAMS >
-inline void setSafeNativeHandle(ENV* env, jobject obj, PARAMS&&... params)
-{
- static_assert(!std::is_array< T >::value, "Array is not supported!");
-
- std::unique_ptr< Detail::HandleHolder< T > > p(
- new Detail::HandleHolder< T >{ new T{ std::forward< PARAMS >(params)... } });
-
- env->SetLongField(obj, g_field_mNativeHandle, reinterpret_cast< jlong >(p.get()));
-
- if (env->ExceptionCheck()) return;
-
- p.release();
-}
-
-template< typename ENV >
-void releaseNativeHandle(ENV* env, jobject obj)
-{
- auto handleHolder = reinterpret_cast< Detail::BaseHandleHolder* >(
- env->GetLongField(obj, g_field_mNativeHandle));
-
- delete handleHolder;
-
- env->SetLongField(obj, g_field_mNativeHandle, 0);
-}
-
-
-template< typename T >
-inline T& getNativeHandleAs(JNIEnv* env, jobject obj)
-{
- auto handleHolder = static_cast< Detail::HandleHolder< T >* >(Detail::getNativeHandle(env, obj));
-
- if (!handleHolder)
- {
- env->ThrowNew(env->FindClass(EXC_NAME_ILLEGAL_STATE), "Internal handle is null!");
- }
-
- return *handleHolder->m_ptr;
-}
-
-template< typename T >
-inline T& getNativeHandleAs(JNIEnvWrapper* env, jobject obj)
-{
- getNativeHandleAs< T >(env->get(), obj);
- if (env->ExceptionCheck()) throw JavaException();
-}
-
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_RcsObject_nativeDispose(JNIEnv*, jobject);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // JNI_RCS_OBJECT_H_
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-#include "JniRcsRemoteResourceObject.h"
-
-#include "JniRcsObject.h"
-#include "JniRcsResourceAttributes.h"
-#include "JavaClasses.h"
-#include "JavaExceptions.h"
-#include "JavaGlobalRef.h"
-#include "Log.h"
-#include "ScopedEnv.h"
-#include "Verify.h"
-
-#include "RCSRemoteResourceObject.h"
-
-using namespace OIC::Service;
-
-#define LOG_TAG "JNI-RCSRemoteResourceObject"
-
-#define CLS_NAME_RESOURCE_STATE CLS_NAME_REMOTERESOURCEOBJECT "$ResourceState"
-#define CLS_NAME_CACHE_STATE CLS_NAME_REMOTERESOURCEOBJECT "$CacheState"
-
-#define CLS_NAME_ON_STATE_CHANGED_LISTENER CLS_NAME_REMOTERESOURCEOBJECT "$OnStateChangedListener"
-#define CLS_NAME_ON_CACHE_UPDATED_LISTENER CLS_NAME_REMOTERESOURCEOBJECT "$OnCacheUpdatedListener"
-#define CLS_NAME_ON_REMOTE_ATTRIBUTES_RECEIVED_LISTENER \
- CLS_NAME_REMOTERESOURCEOBJECT "$OnRemoteAttributesReceivedListener"
-
-namespace
-{
- jclass g_cls_RCSRemoteResourceObject;
- jclass g_cls_ResourceState;
-
- jmethodID g_ctor_RCSRemoteResourceObject;
-
- jmethodID g_method_onStateChanged;
- jmethodID g_method_onCacheUpdated;
- jmethodID g_method_onAttributesReceived;
-
- jobject g_obj_ResourceState_None;
- jobject g_obj_ResourceState_Requested;
- jobject g_obj_ResourceState_Alive;
- jobject g_obj_ResourceState_LostSignal;
- jobject g_obj_ResourceState_Destoryed;
-
- jobject g_obj_CacheState_None;
- jobject g_obj_CacheState_Unready;
- jobject g_obj_CacheState_Ready;
- jobject g_obj_CacheState_LostSignal;
-
-
- inline jobjectArray toJavaStringArray(JNIEnv* env, const std::vector< std::string >& vec)
- {
- jobjectArray arrayObj = env->NewObjectArray(vec.size(), g_cls_String, nullptr);
- if (!arrayObj) return nullptr;
- for (size_t i = 0; i < vec.size(); ++i)
- {
- jstring strObj = env->NewStringUTF(vec[i].c_str());
- VERIFY_NO_EXC_RET_DEF(env);
-
- env->SetObjectArrayElement(arrayObj, i, strObj);
- VERIFY_NO_EXC_RET_DEF(env);
-
- env->DeleteLocalRef(strObj);
- }
- return arrayObj;
- }
-
- template < typename ENV >
- inline jobject convertResourceState(ENV* env, ResourceState state)
- {
- switch (state)
- {
- case ResourceState::NONE: return g_obj_ResourceState_None;
- case ResourceState::REQUESTED: return g_obj_ResourceState_Requested;
- case ResourceState::ALIVE: return g_obj_ResourceState_Alive;
- case ResourceState::LOST_SIGNAL: return g_obj_ResourceState_LostSignal;
- case ResourceState::DESTROYED: return g_obj_ResourceState_Destoryed;
- }
-
- throwRCSException(env, "Failed to convert ResourceState");
- return { };
- }
-
- inline jobject convertCacheState(JNIEnv* env, CacheState state)
- {
- switch (state)
- {
- case CacheState::NONE: return g_obj_CacheState_None;
- case CacheState::UNREADY: return g_obj_CacheState_Unready;
- case CacheState::READY: return g_obj_CacheState_Ready;
- case CacheState::LOST_SIGNAL: return g_obj_CacheState_LostSignal;
- }
-
- throwRCSException(env, "Failed to convert CacheState");
- return { };
- }
-
- inline RCSRemoteResourceObject::Ptr& getResource(JNIEnv* env, jobject obj) noexcept
- {
- return getNativeHandleAs< RCSRemoteResourceObject::Ptr >(env, obj);
- }
-
- void onStateChanged(ResourceState newState, const JavaGlobalRef& listener)
- {
- ScopedEnvWrapper env;
- EXPECT(env, "env is null!");
-
- try
- {
- env->CallVoidMethod(listener, g_method_onStateChanged,
- convertResourceState(env.get(), newState));
- }
- catch (const JavaException&)
- {
- env->ExceptionDescribe();
- env->ExceptionClear();
- }
- }
-
- void onCacheUpdated(const RCSResourceAttributes& attrs, const JavaGlobalRef& listener)
- {
- LOGD("onCacheUpdated");
-
- ScopedEnvWrapper env;
- EXPECT(env, "env is null!");
-
- try
- {
- env->CallVoidMethod(listener, g_method_onCacheUpdated,
- newAttributesObject(env.get(), attrs));
- }
- catch (const JavaException&)
- {
- env->ExceptionDescribe();
- env->ExceptionClear();
- }
- }
-
- void onRemoteAttributesReceived(const RCSResourceAttributes& attrs, int errorCode,
- const JavaGlobalRef& listener)
- {
- ScopedEnvWrapper env;
- EXPECT(env, "env is null!");
-
- try
- {
- env->CallVoidMethod(listener, g_method_onAttributesReceived,
- newAttributesObject(env.get(), attrs), errorCode);
- }
- catch (const JavaException&)
- {
- env->ExceptionDescribe();
- env->ExceptionClear();
- }
- }
-}
-
-
-void initRCSRemoteResourceObject(JNIEnvWrapper* env)
-{
- g_cls_RCSRemoteResourceObject = env->FindClassAsGlobalRef(CLS_NAME_REMOTERESOURCEOBJECT);
-
- g_ctor_RCSRemoteResourceObject = env->GetConstructorID(g_cls_RCSRemoteResourceObject, "()V");
-
- auto clsOnStateChangedListener = env->FindClass(CLS_NAME_ON_STATE_CHANGED_LISTENER);
- g_method_onStateChanged = env->GetMethodID(clsOnStateChangedListener, "onStateChanged",
- "(" AS_SIG(CLS_NAME_RESOURCE_STATE) ")V");
-
- auto clsOnCacheUpdatedListener = env->FindClass(CLS_NAME_ON_CACHE_UPDATED_LISTENER);
- g_method_onCacheUpdated = env->GetMethodID(clsOnCacheUpdatedListener, "onCacheUpdated",
- "(" AS_SIG(CLS_NAME_RESOURCEATTRIBUTES) ")V");
-
- auto clsOnRemoteAttributesReceivedListener =
- env->FindClass(CLS_NAME_ON_REMOTE_ATTRIBUTES_RECEIVED_LISTENER);
- g_method_onAttributesReceived = env->GetMethodID(clsOnRemoteAttributesReceivedListener,
- "onAttributesReceived", "(" AS_SIG(CLS_NAME_RESOURCEATTRIBUTES) "I)V");
-
- auto clsResourceState = env->FindClass(CLS_NAME_RESOURCE_STATE);
-
- g_obj_ResourceState_None = env->NewGlobalRef(env->GetStaticObjectField(clsResourceState,
- "NONE", AS_SIG(CLS_NAME_RESOURCE_STATE)));
-
- g_obj_ResourceState_Requested = env->NewGlobalRef(env->GetStaticObjectField(clsResourceState,
- "REQUESTED", AS_SIG(CLS_NAME_RESOURCE_STATE)));
-
- g_obj_ResourceState_Alive = env->NewGlobalRef(env->GetStaticObjectField(clsResourceState,
- "ALIVE", AS_SIG(CLS_NAME_RESOURCE_STATE)));
-
- g_obj_ResourceState_LostSignal = env->NewGlobalRef(env->GetStaticObjectField(clsResourceState,
- "LOST_SIGNAL", AS_SIG(CLS_NAME_RESOURCE_STATE)));
-
- g_obj_ResourceState_Destoryed = env->NewGlobalRef(env->GetStaticObjectField(clsResourceState,
- "DESTROYED", AS_SIG(CLS_NAME_RESOURCE_STATE)));
-
- auto clsCacheState = env->FindClass(CLS_NAME_CACHE_STATE);
-
- g_obj_CacheState_None = env->NewGlobalRef(env->GetStaticObjectField(clsCacheState,
- "NONE", AS_SIG(CLS_NAME_CACHE_STATE)));
-
- g_obj_CacheState_Unready = env->NewGlobalRef(env->GetStaticObjectField(clsCacheState,
- "UNREADY", AS_SIG(CLS_NAME_CACHE_STATE)));
-
- g_obj_CacheState_Ready = env->NewGlobalRef(env->GetStaticObjectField(clsCacheState,
- "READY", AS_SIG(CLS_NAME_CACHE_STATE)));
-
- g_obj_CacheState_LostSignal = env->NewGlobalRef(env->GetStaticObjectField(clsCacheState,
- "LOST_SIGNAL", AS_SIG(CLS_NAME_CACHE_STATE)));
-
-
-}
-
-void clearRCSRemoteResourceObject(JNIEnvWrapper* env)
-{
- env->DeleteGlobalRef(g_cls_RCSRemoteResourceObject);
- env->DeleteGlobalRef(g_cls_ResourceState);
-
- env->DeleteGlobalRef(g_obj_ResourceState_None);
- env->DeleteGlobalRef(g_obj_ResourceState_Requested);
- env->DeleteGlobalRef(g_obj_ResourceState_Alive);
- env->DeleteGlobalRef(g_obj_ResourceState_LostSignal);
- env->DeleteGlobalRef(g_obj_ResourceState_Destoryed);
-
- env->DeleteGlobalRef(g_obj_CacheState_None);
- env->DeleteGlobalRef(g_obj_CacheState_Unready);
- env->DeleteGlobalRef(g_obj_CacheState_Ready);
- env->DeleteGlobalRef(g_obj_CacheState_LostSignal);
-}
-
-jobject newRemoteResourceObject(JNIEnvWrapper* env)
-{
- return env->NewObject(g_cls_RCSRemoteResourceObject, g_ctor_RCSRemoteResourceObject);
-}
-
-JNIEXPORT jboolean JNICALL
-Java_org_iotivity_service_client_RcsRemoteResourceObject_nativeIsMonitoring
-(JNIEnv* env, jobject obj)
-{
- LOGD("nativeIsMonitoring");
- auto res = getResource(env, obj);
- VERIFY_NO_EXC_RET_DEF(env);
-
- return res->isMonitoring();
-}
-
-JNIEXPORT jboolean JNICALL
-Java_org_iotivity_service_client_RcsRemoteResourceObject_nativeIsCaching
-(JNIEnv* env, jobject obj)
-{
- LOGD("nativeIsCaching");
- auto res = getResource(env, obj);
- VERIFY_NO_EXC_RET_DEF(env);
-
- return res->isCaching();
-}
-
-JNIEXPORT jboolean JNICALL
-Java_org_iotivity_service_client_RcsRemoteResourceObject_nativeIsObservable
-(JNIEnv* env, jobject obj)
-{
- LOGD("nativeIsObservable");
- auto res = getResource(env, obj);
- VERIFY_NO_EXC_RET_DEF(env);
-
- return res->isObservable();
-}
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_client_RcsRemoteResourceObject_nativeStartMonitoring
-(JNIEnv* env, jobject obj, jobject listener)
-{
- LOGD("nativeStartMonitoring");
- EXPECT(listener, "listener is null.");
-
- auto res = getResource(env, obj);
- VERIFY_NO_EXC(env);
-
- try
- {
- res->startMonitoring(
- std::bind(onStateChanged, std::placeholders::_1, JavaGlobalRef{ env, listener }));
- }
- catch (const RCSBadRequestException& e)
- {
- env->ThrowNew(env->FindClass(EXC_NAME_ILLEGAL_STATE), e.what());
- }
-}
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_client_RcsRemoteResourceObject_nativeStopMonitoring
-(JNIEnv* env, jobject obj)
-{
- LOGD("nativeStopMonitoring");
-
- auto res = getResource(env, obj);
- VERIFY_NO_EXC(env);
-
- res->stopMonitoring();
-}
-
-JNIEXPORT jobject JNICALL
-Java_org_iotivity_service_client_RcsRemoteResourceObject_nativeGetState
-(JNIEnv* env, jobject obj)
-{
- LOGD("nativeGetState");
-
- auto res = getResource(env, obj);
- VERIFY_NO_EXC_RET_DEF(env);
-
- return convertResourceState(env, res->getState());
-}
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_client_RcsRemoteResourceObject_nativeStartCaching
-(JNIEnv* env, jobject obj, jobject listener)
-{
- LOGD("nativeStartCaching");
-
- auto res = getResource(env, obj);
- VERIFY_NO_EXC(env);
-
- try
- {
- if (listener)
- {
- res->startCaching(std::bind(onCacheUpdated,
- std::placeholders::_1, JavaGlobalRef{ env, listener }));
- }
- else
- {
- res->startCaching();
- }
- }
- catch (const RCSBadRequestException& e)
- {
- env->ThrowNew(env->FindClass(EXC_NAME_ILLEGAL_STATE), e.what());
- }
-}
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_client_RcsRemoteResourceObject_nativeStopCaching
-(JNIEnv* env, jobject obj)
-{
- LOGD("nativeStopCaching");
-
- auto res = getResource(env, obj);
- VERIFY_NO_EXC(env);
-
- res->stopCaching();
-}
-
-JNIEXPORT jobject JNICALL
-Java_org_iotivity_service_client_RcsRemoteResourceObject_nativeGetCacheState
-(JNIEnv* env, jobject obj)
-{
- LOGD("nativeGetCacheState");
-
- auto res = getResource(env, obj);
- VERIFY_NO_EXC_RET_DEF(env);
-
- return convertCacheState(env, res->getCacheState());
-}
-
-JNIEXPORT jboolean JNICALL
-Java_org_iotivity_service_client_RcsRemoteResourceObject_nativeIsCachedAvailable
-(JNIEnv* env, jobject obj)
-{
- LOGD("nativeIsCachedAvailable");
-
- auto res = getResource(env, obj);
- VERIFY_NO_EXC_RET_DEF(env);
-
- try
- {
- return res->isCachedAvailable();
- }
- catch (const RCSBadRequestException& e)
- {
- env->ThrowNew(env->FindClass(EXC_NAME_ILLEGAL_STATE), e.what());
- return false;
- }
-}
-
-JNIEXPORT jobject JNICALL
-Java_org_iotivity_service_client_RcsRemoteResourceObject_nativeGetCachedAttributes
-(JNIEnv* env, jobject obj)
-{
- LOGD("nativeGetCachedAttributes");
-
- auto res = getResource(env, obj);
- VERIFY_NO_EXC_RET_DEF(env);
-
- try
- {
- auto attrs = res->getCachedAttributes();
- VERIFY_NO_EXC_RET_DEF(env);
-
- return newAttributesObject(env, attrs);
- }
- catch (const RCSBadRequestException& e)
- {
- env->ThrowNew(env->FindClass(EXC_NAME_ILLEGAL_STATE), e.what());
- return { };
- }
-}
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_client_RcsRemoteResourceObject_nativeGetRemoteAttributes
-(JNIEnv* env, jobject obj, jobject listener)
-{
- LOGD("nativeGetRemoteAttributes");
- EXPECT(listener, "listener is null.");
-
- auto res = getResource(env, obj);
- VERIFY_NO_EXC(env);
-
- try
- {
- res->getRemoteAttributes(std::bind(onRemoteAttributesReceived,
- std::placeholders::_1, std::placeholders::_2, JavaGlobalRef{ env, listener }));
- }
- catch (const RCSPlatformException& e) {
- throwPlatformException(env, e);
- }
-}
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_client_RcsRemoteResourceObject_nativeSetRemoteAttributes
-(JNIEnv* env, jobject obj, jobject attrsObj, jobject listener)
-{
- LOGD("nativeSetRemoteAttributes");
- auto res = getResource(env, obj);
- VERIFY_NO_EXC(env);
-
- RCSResourceAttributes attrs = toNativeAttributes(env, attrsObj);
- VERIFY_NO_EXC(env);
-
- try
- {
- res->setRemoteAttributes(attrs, std::bind(onRemoteAttributesReceived,
- std::placeholders::_1, std::placeholders::_2, JavaGlobalRef{ env, listener }));
- }
- catch (const RCSPlatformException& e) {
- throwPlatformException(env, e);
- }
-}
-
-JNIEXPORT jstring JNICALL
-Java_org_iotivity_service_client_RcsRemoteResourceObject_nativeGetUri
-(JNIEnv* env, jobject obj)
-{
- LOGD("nativeGetUri");
-
- auto res = getResource(env, obj);
- VERIFY_NO_EXC_RET_DEF(env);
-
- return env->NewStringUTF(res->getUri().c_str());
-}
-
-JNIEXPORT jstring JNICALL
-Java_org_iotivity_service_client_RcsRemoteResourceObject_nativeGetAddress
-(JNIEnv* env, jobject obj)
-{
- LOGD("nativeGetAddress");
- auto res = getResource(env, obj);
- VERIFY_NO_EXC_RET_DEF(env);
-
- return env->NewStringUTF(res->getAddress().c_str());
-}
-
-JNIEXPORT jobjectArray JNICALL
-Java_org_iotivity_service_client_RcsRemoteResourceObject_nativeGetTypes
-(JNIEnv* env, jobject obj)
-{
- LOGD("nativeGetTypes");
- auto res = getResource(env, obj);
- VERIFY_NO_EXC_RET_DEF(env);
-
- return toJavaStringArray(env, res->getTypes());
-}
-
-JNIEXPORT jobjectArray JNICALL
-Java_org_iotivity_service_client_RcsRemoteResourceObject_nativeGetInterfaces
-(JNIEnv* env, jobject obj)
-{
- LOGD("nativeGetInterfaces");
-
- auto res = getResource(env, obj);
- VERIFY_NO_EXC_RET_DEF(env);
-
- return toJavaStringArray(env, res->getInterfaces());
-}
-
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-#ifndef JNI_RE_RCS_REMOTE_RESOURCE_OBJECT_H_
-#define JNI_RE_RCS_REMOTE_RESOURCE_OBJECT_H_
-
-#include <jni.h>
-
-class JNIEnvWrapper;
-
-void initRCSRemoteResourceObject(JNIEnvWrapper*);
-void clearRCSRemoteResourceObject(JNIEnvWrapper*);
-
-jobject newRemoteResourceObject(JNIEnvWrapper*);
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-JNIEXPORT jboolean JNICALL
-Java_org_iotivity_service_client_RcsRemoteResourceObject_nativeIsMonitoring
-(JNIEnv*, jobject);
-
-JNIEXPORT jboolean JNICALL
-Java_org_iotivity_service_client_RcsRemoteResourceObject_nativeIsCaching
-(JNIEnv*, jobject);
-
-JNIEXPORT jboolean JNICALL
-Java_org_iotivity_service_client_RcsRemoteResourceObject_nativeIsObservable
-(JNIEnv*, jobject);
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_client_RcsRemoteResourceObject_nativeStartMonitoring
-(JNIEnv*, jobject, jobject);
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_client_RcsRemoteResourceObject_nativeStopMonitoring
-(JNIEnv*, jobject);
-
-JNIEXPORT jobject JNICALL
-Java_org_iotivity_service_client_RcsRemoteResourceObject_nativeGetState
-(JNIEnv*, jobject);
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_client_RcsRemoteResourceObject_nativeStartCaching
-(JNIEnv*, jobject, jobject cacheUpdateListener);
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_client_RcsRemoteResourceObject_nativeStopCaching
-(JNIEnv*, jobject);
-
-JNIEXPORT jobject JNICALL
-Java_org_iotivity_service_client_RcsRemoteResourceObject_nativeGetCacheState
-(JNIEnv*, jobject);
-
-JNIEXPORT jboolean JNICALL
-Java_org_iotivity_service_client_RcsRemoteResourceObject_nativeIsCachedAvailable
-(JNIEnv*, jobject);
-
-JNIEXPORT jobject JNICALL
-Java_org_iotivity_service_client_RcsRemoteResourceObject_nativeGetCachedAttributes
-(JNIEnv*, jobject);
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_client_RcsRemoteResourceObject_nativeGetRemoteAttributes
-(JNIEnv*, jobject, jobject listener);
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_client_RcsRemoteResourceObject_nativeSetRemoteAttributes
-(JNIEnv*, jobject, jobject attrs, jobject listener);
-
-JNIEXPORT jstring JNICALL
-Java_org_iotivity_service_client_RcsRemoteResourceObject_nativeGetUri
-(JNIEnv*, jobject);
-
-JNIEXPORT jstring JNICALL
-Java_org_iotivity_service_client_RcsRemoteResourceObject_nativeGetAddress
-(JNIEnv*, jobject);
-
-JNIEXPORT jobjectArray JNICALL
-Java_org_iotivity_service_client_RcsRemoteResourceObject_nativeGetTypes
-(JNIEnv*, jobject);
-
-JNIEXPORT jobjectArray JNICALL
-Java_org_iotivity_service_client_RcsRemoteResourceObject_nativeGetInterfaces
-(JNIEnv*, jobject);
-
-#ifdef __cplusplus
-}
-#endif
-#endif // JNI_RE_RCS_REMOTE_RESOURCE_OBJECT_H_
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-#include "JniRcsResourceAttributes.h"
-
-#include "JniRcsObject.h"
-#include "JavaLocalRef.h"
-#include "JniRcsValue.h"
-#include "Log.h"
-#include "Verify.h"
-
-using namespace OIC::Service;
-
-#define LOG_TAG "JNI-RCSResourceAttributes"
-
-namespace
-{
- jclass g_cls_RCSResourceAttributes;
-
- jmethodID g_ctor_RCSResourceAttributes;
-
- jfieldID g_field_mCache;
-}
-
-void initRCSResourceAttributes(JNIEnvWrapper* env)
-{
- g_cls_RCSResourceAttributes = env->FindClassAsGlobalRef(CLS_NAME_RESOURCEATTRIBUTES);
- g_ctor_RCSResourceAttributes = env->GetConstructorID(g_cls_RCSResourceAttributes, "()V");
-
- g_field_mCache = env->GetFieldID(g_cls_RCSResourceAttributes, "mCache", AS_SIG(CLS_NAME_MAP));
-}
-
-void clearRCSResourceAttributes(JNIEnvWrapper* env)
-{
- env->DeleteGlobalRef(g_cls_RCSResourceAttributes);
-}
-
-jobject newAttributesObject(JNIEnv* env, const RCSResourceAttributes& attrs)
-{
- jobject obj = env->NewObject(g_cls_RCSResourceAttributes, g_ctor_RCSResourceAttributes);
- VERIFY_NO_EXC_RET_DEF(env);
-
- setSafeNativeHandle< RCSResourceAttributes >(env, obj, attrs);
-
- return obj;
-}
-
-jobject newAttributesObject(JNIEnvWrapper* env, const RCSResourceAttributes& attrs)
-{
- jobject obj = env->NewObject(g_cls_RCSResourceAttributes, g_ctor_RCSResourceAttributes);
-
- setSafeNativeHandle< RCSResourceAttributes >(env, obj, attrs);
-
- return obj;
-}
-
-RCSResourceAttributes toNativeAttributes(JNIEnv* env, jobject attrsObj)
-{
- EXPECT_RET(attrsObj, "attrsObj is null!", { });
-
- JNIEnvWrapper envWrapper{ env };
-
- try
- {
- return toNativeAttributes(&envWrapper, attrsObj);
- }
- catch (const JavaException&)
- {
- return {};
- }
-}
-
-RCSResourceAttributes toNativeAttributes(JNIEnvWrapper* env, jobject attrsObj)
-{
- EXPECT_RET(attrsObj, "attrsObj is null!", { });
-
- RCSResourceAttributes attrs;
-
- if (hasNativeHandle(env, attrsObj))
- {
- attrs = getNativeHandleAs< RCSResourceAttributes >(env, attrsObj);
- }
-
- writeNativeAttributesFromMap(env,
- JavaLocalObject{ env, env->GetObjectField(attrsObj, g_field_mCache) }, attrs);
-
- return attrs;
-}
-
-void writeNativeAttributesFromMap(JNIEnv* env, jobject mapObj, RCSResourceAttributes& targetAttrs)
-{
- JNIEnvWrapper envWrapper{ env };
-
- try
- {
- return writeNativeAttributesFromMap(&envWrapper, mapObj, targetAttrs);
- }
- catch (const JavaException&)
- {
- }
-}
-
-void writeNativeAttributesFromMap(JNIEnvWrapper* env, jobject mapObj,
- RCSResourceAttributes& targetAttrs)
-{
- JavaLocalObject setObj{ env, invoke_Map_entrySet(env, mapObj) };
- JavaLocalObject iterObj{ env, invoke_Set_iterator(env, setObj) };
-
- while (invoke_Iterator_hasNext(env, iterObj))
- {
- JavaLocalObject entryObj{ env, invoke_Iterator_next(env, iterObj) };
- JavaLocalObject keyObj{ env, invoke_MapEntry_getKey(env, entryObj) };
- JavaLocalObject valueObj{ env, invoke_MapEntry_getValue(env, entryObj) };
-
- auto key = toStdString(env, static_cast< jstring >(keyObj.get()));
-
- targetAttrs[std::move(key)] = toNativeAttrsValue(env, valueObj);
- }
-}
-
-JNIEXPORT jboolean JNICALL Java_org_iotivity_service_RcsResourceAttributes_nativeIsEmpty
-(JNIEnv* env, jobject obj)
-{
- LOGD("isEmpty");
- EXPECT_RET(hasNativeHandle(env, obj), "no native handle.", true);
-
- auto& attrs = getNativeHandleAs< RCSResourceAttributes >(env, obj);
- VERIFY_NO_EXC_RET_DEF(env);
-
- return attrs.empty();
-}
-
-JNIEXPORT jint JNICALL Java_org_iotivity_service_RcsResourceAttributes_nativeSize
-(JNIEnv* env, jobject obj)
-{
- LOGD("size");
- EXPECT_RET(hasNativeHandle(env, obj), "no native handle.", 0);
-
- auto& attrs = getNativeHandleAs< RCSResourceAttributes >(env, obj);
- VERIFY_NO_EXC_RET_DEF(env);
-
- return attrs.size();
-}
-
-JNIEXPORT jboolean JNICALL Java_org_iotivity_service_RcsResourceAttributes_nativeRemove
-(JNIEnv* env, jobject obj, jstring keyObj)
-{
- LOGD("remove");
- EXPECT_RET_DEF(keyObj, "Key is null.");
- EXPECT_RET_DEF(hasNativeHandle(env, obj), "no native handle.");
-
- auto& attrs = getNativeHandleAs< RCSResourceAttributes >(env, obj);
- VERIFY_NO_EXC_RET_DEF(env);
- const auto& key = toStdString(env, keyObj);
- VERIFY_NO_EXC_RET_DEF(env);
-
- auto ret = attrs.erase(key);
-
- if (attrs.empty()) releaseNativeHandle(env, obj);
-
- return ret;
-}
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_RcsResourceAttributes_nativeClear
-(JNIEnv* env, jobject obj)
-{
- LOGD("clear");
-
- releaseNativeHandle(env, obj);
-}
-
-JNIEXPORT jboolean JNICALL Java_org_iotivity_service_RcsResourceAttributes_nativeContains
-(JNIEnv *env, jobject obj, jstring keyObj)
-{
- LOGD("contains");
- EXPECT_RET(keyObj, "Key is null.", false);
- EXPECT_RET(hasNativeHandle(env, obj), "no native handle.", false);
-
- auto& attrs = getNativeHandleAs< RCSResourceAttributes >(env, obj);
- VERIFY_NO_EXC_RET_DEF(env);
- const auto& key = toStdString(env, keyObj);
- VERIFY_NO_EXC_RET_DEF(env);
- return attrs.contains(key);
-}
-
-JNIEXPORT void JNICALL Java_org_iotivity_service_RcsResourceAttributes_nativeAddKeys
-(JNIEnv *env, jobject obj, jstring setObj)
-{
- LOGD("addKeys");
- EXPECT(setObj, "set is null.");
- EXPECT(hasNativeHandle(env, obj), "no native handle.");
-
- auto& attrs = getNativeHandleAs< RCSResourceAttributes >(env, obj);
- VERIFY_NO_EXC(env);
-
- for (const auto& keyValue : attrs)
- {
- JavaLocalString localObj{ env, env->NewStringUTF(keyValue.key().c_str()) };
- VERIFY_NO_EXC(env);
-
- invoke_Collection_add(env, setObj, localObj);
- VERIFY_NO_EXC(env);
- }
-}
-
-JNIEXPORT jobject JNICALL Java_org_iotivity_service_RcsResourceAttributes_nativeExtract
-(JNIEnv* env, jobject obj, jstring keyObj)
-{
- LOGD("extract");
- EXPECT_RET_DEF(keyObj, "Key is null.");
- EXPECT_RET_DEF(hasNativeHandle(env, obj), "no native handle.");
-
- auto& attrs = getNativeHandleAs< RCSResourceAttributes >(env, obj);
- VERIFY_NO_EXC_RET_DEF(env);
-
- const auto& key = toStdString(env, keyObj);
- VERIFY_NO_EXC_RET_DEF(env);
-
- EXPECT_RET_DEF(attrs.contains(key), "no matched value");
-
- jobject valueObj = newRCSValueObject(env, attrs[key]);
- VERIFY_NO_EXC_RET_DEF(env);
-
- attrs.erase(key);
- if (attrs.empty()) releaseNativeHandle(env, obj);
- return valueObj;
-}
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_RcsResourceAttributes_nativeExtractAll
-(JNIEnv* env, jobject obj, jobject mapObj)
-{
- LOGD("extractAll");
- EXPECT(mapObj, "Map is null.");
- EXPECT(hasNativeHandle(env, obj), "no native handle.");
-
- auto& attrs = getNativeHandleAs< RCSResourceAttributes >(env, obj);
- VERIFY_NO_EXC(env);
-
- for (const auto& p : attrs) {
- JavaLocalObject keyObj{ env, newStringObject(env, p.key()) };
- VERIFY_NO_EXC(env);
-
- JavaLocalObject valueObj{ env, newRCSValueObject(env, p.value()) };
- VERIFY_NO_EXC(env);
-
- invoke_Map_put(env, mapObj, keyObj, valueObj);
- VERIFY_NO_EXC(env);
- }
-
- attrs.clear();
- releaseNativeHandle(env, obj);
-}
-
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-#ifndef JNI_RCS_RESOURCE_ATTRIBUTES_H_
-#define JNI_RCS_RESOURCE_ATTRIBUTES_H_
-
-#include <jni.h>
-
-namespace OIC
-{
- namespace Service
- {
- class RCSResourceAttributes;
- }
-}
-
-class JNIEnvWrapper;
-
-void initRCSResourceAttributes(JNIEnvWrapper*);
-void clearRCSResourceAttributes(JNIEnvWrapper*);
-
-jobject newAttributesObject(JNIEnv*, const OIC::Service::RCSResourceAttributes&);
-jobject newAttributesObject(JNIEnvWrapper*, const OIC::Service::RCSResourceAttributes&);
-
-OIC::Service::RCSResourceAttributes toNativeAttributes(JNIEnv*, jobject);
-OIC::Service::RCSResourceAttributes toNativeAttributes(JNIEnvWrapper*, jobject);
-
-void writeNativeAttributesFromMap(JNIEnv*, jobject mapObj,
- OIC::Service::RCSResourceAttributes& targetAttrs);
-void writeNativeAttributesFromMap(JNIEnvWrapper*, jobject mapObj,
- OIC::Service::RCSResourceAttributes& targetAttrs);
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-JNIEXPORT jboolean JNICALL
-Java_org_iotivity_service_RcsResourceAttributes_nativeIsEmpty(JNIEnv*, jobject);
-
-JNIEXPORT jint JNICALL
-Java_org_iotivity_service_RcsResourceAttributes_nativeSize(JNIEnv*, jobject);
-
-JNIEXPORT jboolean JNICALL
-Java_org_iotivity_service_RcsResourceAttributes_nativeRemove(JNIEnv*, jobject, jstring keyObj);
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_RcsResourceAttributes_nativeClear(JNIEnv*, jobject);
-
-JNIEXPORT jboolean JNICALL
-Java_org_iotivity_service_RcsResourceAttributes_nativeContains(JNIEnv*, jobject, jstring keyObj);
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_RcsResourceAttributes_nativeAddKeys(JNIEnv*, jobject, jstring setObj);
-
-JNIEXPORT jobject JNICALL
-Java_org_iotivity_service_RcsResourceAttributes_nativeExtract(JNIEnv*, jobject, jstring keyObj);
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_RcsResourceAttributes_nativeExtractAll(JNIEnv*, jobject, jobject);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif //JNI_RCS_RESOURCE_ATTRIBUTES_H_
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-#include "JniRcsResourceObject.h"
-
-#include "JniRcsObject.h"
-#include "JniRcsResourceAttributes.h"
-#include "JavaClasses.h"
-#include "JavaExceptions.h"
-#include "JavaGlobalRef.h"
-#include "JniRcsValue.h"
-#include "Log.h"
-#include "ScopedEnv.h"
-#include "Verify.h"
-
-#include "RCSResourceObject.h"
-#include "RCSResponse.h"
-#include "RCSRequest.h"
-#include "RequestHandler.h"
-
-#define LOG_TAG "JNI-RCSResourceObject"
-
-#define CLS_NAME_RCS_RESOURCE_OBJECT PACKAGE_NAME "/server/RcsResourceObject"
-#define CLS_NAME_RCS_REQUEST PACKAGE_NAME "/server/RcsRequest"
-
-#define CLS_NAME_AUTO_NOTIFY_POLICY CLS_NAME_RCS_RESOURCE_OBJECT "$AutoNotifyPolicy"
-#define CLS_NAME_SET_REQUEST_HANDLER_POLICY CLS_NAME_RCS_RESOURCE_OBJECT "$SetRequestHandlerPolicy"
-
-#define CLS_NAME_GET_REQUEST_HANDLER CLS_NAME_RCS_RESOURCE_OBJECT "$GetRequestHandler"
-#define CLS_NAME_SET_REQUEST_HANDLER CLS_NAME_RCS_RESOURCE_OBJECT "$SetRequestHandler"
-#define CLS_NAME_ON_ATTRIBUTE_UPDATESD_LISTENER \
- CLS_NAME_RCS_RESOURCE_OBJECT "$OnAttributeUpdatedListener"
-
-#define CLS_NAME_RCS_RESPONSE PACKAGE_NAME "/server/RcsResponse"
-
-#define CLS_NAME_RCS_GET_RESPONSE PACKAGE_NAME "/server/RcsGetResponse"
-#define CLS_NAME_RCS_SET_RESPONSE PACKAGE_NAME "/server/RcsSetResponse"
-#define CLS_NAME_RCS_SET_RESPONSE_ACCEPTANCE_METHOD CLS_NAME_RCS_SET_RESPONSE "$AcceptanceMethod"
-
-using namespace OIC::Service;
-
-namespace
-{
- jclass g_cls_RCSRequest;
- jclass g_cls_RCSResourceObject;
-
- jmethodID g_ctor_RCSRequest;
- jmethodID g_ctor_RCSResourceObject;
-
- jmethodID g_method_GetRequestHandler_onGetRequested;
- jmethodID g_method_SetRequestHandler_onSetRequested;
- jmethodID g_method_OnAttributeUpdatedListener_onAttributeUpdated;
-
- jfieldID g_field_RCSResponse_mErrorCode;
- jfieldID g_field_RCSResponse_mAttrs;
- jfieldID g_field_RCSSetResponse_mAcceptanceMethod;
-
- jobject g_obj_RCSSetResponse_AcceptanceMethod_DEFAULT;
- jobject g_obj_RCSSetResponse_AcceptanceMethod_ACCEPT;
- jobject g_obj_RCSSetResponse_AcceptanceMethod_IGNORE;
-
- jobject g_obj_AutoNotifyPolicy_NEVER;
- jobject g_obj_AutoNotifyPolicy_ALWAYS;
- jobject g_obj_AutoNotifyPolicy_UPDATED;
-
- jobject g_obj_SetRequestHandlerPolicy_NEVER;
- jobject g_obj_SetRequestHandlerPolicy_ACCEPT;
-
- inline RCSResourceObject::Ptr& getResource(JNIEnv* env, jobject obj)
- {
- return getNativeHandleAs< RCSResourceObject::Ptr >(env, obj);
- }
-
- inline RCSResourceObject::AutoNotifyPolicy convertAutoNotifyPolicy(JNIEnv* env, jobject obj)
- {
- if (env->IsSameObject(g_obj_AutoNotifyPolicy_NEVER, obj))
- {
- return RCSResourceObject::AutoNotifyPolicy::NEVER;
- }
-
- if (env->IsSameObject(g_obj_AutoNotifyPolicy_ALWAYS, obj))
- {
- return RCSResourceObject::AutoNotifyPolicy::ALWAYS;
- }
-
- if (env->IsSameObject(g_obj_AutoNotifyPolicy_UPDATED, obj))
- {
- return RCSResourceObject::AutoNotifyPolicy::UPDATED;
- }
-
- throwRCSException(env, "Failed to convert AutoNotifyPolicy");
- return {};
- }
-
- inline jobject convertAutoNotifyPolicy(JNIEnv* env, RCSResourceObject::AutoNotifyPolicy policy)
- {
- switch(policy)
- {
- case RCSResourceObject::AutoNotifyPolicy::NEVER: return g_obj_AutoNotifyPolicy_NEVER;
- case RCSResourceObject::AutoNotifyPolicy::ALWAYS: return g_obj_AutoNotifyPolicy_ALWAYS;
- case RCSResourceObject::AutoNotifyPolicy::UPDATED: return g_obj_AutoNotifyPolicy_UPDATED;
- }
-
- throwRCSException(env, "Failed to convert AutoNotifyPolicy");
- return {};
- }
-
- inline RCSResourceObject::SetRequestHandlerPolicy convertSetRequestHandlerPolicy(JNIEnv* env,
- jobject obj)
- {
- if (env->IsSameObject(g_obj_SetRequestHandlerPolicy_NEVER, obj))
- {
- return RCSResourceObject::SetRequestHandlerPolicy::NEVER;
- }
-
- if (env->IsSameObject(g_obj_SetRequestHandlerPolicy_ACCEPT, obj))
- {
- return RCSResourceObject::SetRequestHandlerPolicy::ACCEPTANCE;
- }
-
- throwRCSException(env, "Failed to convert SetRequestHandlerPolicy");
- return {};
- }
-
- inline jobject convertSetRequestHandlerPolicy(JNIEnv* env,
- RCSResourceObject::SetRequestHandlerPolicy policy)
- {
- switch(policy)
- {
- case RCSResourceObject::SetRequestHandlerPolicy::NEVER:
- return g_obj_SetRequestHandlerPolicy_NEVER;
- case RCSResourceObject::SetRequestHandlerPolicy::ACCEPTANCE:
- return g_obj_SetRequestHandlerPolicy_ACCEPT;
- }
-
- throwRCSException(env, "Failed to convert SetRequestHandlerPolicy");
- return {};
- }
-
-
- template< typename ENV >
- inline jobject getAttrsObj(ENV& env, jobject responseObj)
- {
- return env->GetObjectField(responseObj, g_field_RCSResponse_mAttrs);
- }
-
- template< typename ENV >
- inline int getErrorCode(ENV& env, jobject responseObj)
- {
- return env->GetIntField(responseObj, g_field_RCSResponse_mErrorCode);
- }
-
- template< typename ENV >
- inline RCSSetResponse::AcceptanceMethod getAcceptanceMethod(ENV& env, jobject responseObj)
- {
- auto methodObj = env->GetObjectField(responseObj, g_field_RCSSetResponse_mAcceptanceMethod);
-
- if (env->IsSameObject(methodObj, g_obj_RCSSetResponse_AcceptanceMethod_IGNORE))
- {
- return RCSSetResponse::AcceptanceMethod::IGNORE;
- }
-
- if (env->IsSameObject(methodObj, g_obj_RCSSetResponse_AcceptanceMethod_ACCEPT))
- {
- return RCSSetResponse::AcceptanceMethod::ACCEPT;
- }
-
- return RCSSetResponse::AcceptanceMethod::DEFAULT;
- }
-
- inline jobject callHandler(ScopedEnvWrapper& env, jobject listener, jmethodID methodId,
- const RCSRequest& request, const RCSResourceAttributes& attrs)
- {
- auto requestObj = env->NewObject(g_cls_RCSRequest, g_ctor_RCSRequest,
- env->NewStringUTF(request.getResourceUri().c_str()));
- auto attrsObj = newAttributesObject(env.get(), attrs);
-
- return env->CallObjectMethod(listener, methodId, requestObj, attrsObj);
- }
-
- template< typename RESPONSE >
- inline RESPONSE createResponse(ScopedEnvWrapper& env, jobject responseObj)
- {
- auto errorCode = getErrorCode(env, responseObj);
- auto responseAttrsObj = getAttrsObj(env, responseObj);
-
- if (responseAttrsObj)
- {
- return RESPONSE::create(toNativeAttributes(env.get(), responseAttrsObj), errorCode);
- }
-
- return RESPONSE::create(errorCode);
- }
-
- RCSGetResponse onGetRequest(const RCSRequest& request, const RCSResourceAttributes& attrs,
- const JavaGlobalRef& listener)
- {
- ScopedEnvWrapper env;
- EXPECT_RET(env, "env is null!", RCSGetResponse::create(-1));
-
- try
- {
- auto responseObj = callHandler(env, listener, g_method_GetRequestHandler_onGetRequested,
- request, attrs);
-
- return createResponse< RCSGetResponse >(env, responseObj);
- }
- catch (const JavaException&)
- {
- env->ExceptionDescribe();
- env->ExceptionClear();
- }
- return RCSGetResponse::create({ }, -1);
- }
-
- RCSSetResponse onSetRequest(const RCSRequest& request, const RCSResourceAttributes& attrs,
- const JavaGlobalRef& listener)
- {
- ScopedEnvWrapper env;
- EXPECT_RET(env, "env is null!", RCSSetResponse::create(-1));
-
- try
- {
- auto responseObj = callHandler(env, listener, g_method_SetRequestHandler_onSetRequested,
- request, attrs);
-
- auto acceptanceMethod = getAcceptanceMethod(env, responseObj);
-
- return createResponse< RCSSetResponse >(env, responseObj).
- setAcceptanceMethod(acceptanceMethod);
- }
- catch (const JavaException&)
- {
- env->ExceptionDescribe();
- env->ExceptionClear();
- }
- return RCSSetResponse::create(-1);
- }
-
-
- void onAttributeUpdated(const RCSResourceAttributes::Value& oldVal,
- const RCSResourceAttributes::Value& newVal, const JavaGlobalRef& listener)
- {
- ScopedEnvWrapper env;
- EXPECT(env, "env is null!");
-
- try
- {
- env->CallVoidMethod(listener, g_method_OnAttributeUpdatedListener_onAttributeUpdated,
- newRCSValueObject(env.get(), oldVal), newRCSValueObject(env.get(), newVal));
- }
- catch (const JavaException&)
- {
- env->ExceptionDescribe();
- env->ExceptionClear();
- }
- }
-
- void initRCSResponse(JNIEnvWrapper* env)
- {
- auto clsRCSResponse = env->FindClass(CLS_NAME_RCS_RESPONSE);
-
- g_field_RCSResponse_mErrorCode = env->GetFieldID(clsRCSResponse, "mErrorCode", "I");
-
- g_field_RCSResponse_mAttrs = env->GetFieldID(clsRCSResponse, "mAttrs",
- AS_SIG(CLS_NAME_RESOURCEATTRIBUTES));
-
- auto clsRCSSetResponse = env->FindClass(CLS_NAME_RCS_SET_RESPONSE);
-
- g_field_RCSSetResponse_mAcceptanceMethod = env->GetFieldID(clsRCSSetResponse,
- "mAcceptanceMethod", AS_SIG(CLS_NAME_RCS_SET_RESPONSE_ACCEPTANCE_METHOD));
-
- auto clsAcceptanceMethod = env->FindClass(CLS_NAME_RCS_SET_RESPONSE_ACCEPTANCE_METHOD);
-
- g_obj_RCSSetResponse_AcceptanceMethod_DEFAULT = env->NewGlobalRef(
- env->GetStaticObjectField(clsAcceptanceMethod, "DEFAULT",
- AS_SIG(CLS_NAME_RCS_SET_RESPONSE_ACCEPTANCE_METHOD)));
-
- g_obj_RCSSetResponse_AcceptanceMethod_ACCEPT = env->NewGlobalRef(
- env->GetStaticObjectField(clsAcceptanceMethod, "ACCEPT",
- AS_SIG(CLS_NAME_RCS_SET_RESPONSE_ACCEPTANCE_METHOD)));
-
- g_obj_RCSSetResponse_AcceptanceMethod_IGNORE = env->NewGlobalRef(
- env->GetStaticObjectField(clsAcceptanceMethod, "IGNORE",
- AS_SIG(CLS_NAME_RCS_SET_RESPONSE_ACCEPTANCE_METHOD)));
- }
-}
-
-void initRCSResourceObject(JNIEnvWrapper* env)
-{
- g_cls_RCSResourceObject = env->FindClassAsGlobalRef(CLS_NAME_RCS_RESOURCE_OBJECT);
-
- g_ctor_RCSResourceObject = env->GetMethodID(g_cls_RCSResourceObject, "<init>", "()V");
-
- g_cls_RCSRequest = env->FindClassAsGlobalRef(CLS_NAME_RCS_REQUEST);
-
- g_ctor_RCSRequest = env->GetMethodID(g_cls_RCSRequest, "<init>",
- "(" AS_SIG(CLS_NAME_STRING) ")V");
-
- auto clsGetRequestHandler = env->FindClass(CLS_NAME_GET_REQUEST_HANDLER);
-
- g_method_GetRequestHandler_onGetRequested = env->GetMethodID(clsGetRequestHandler,
- "onGetRequested",
- "(" AS_SIG(CLS_NAME_RCS_REQUEST) AS_SIG(CLS_NAME_RESOURCEATTRIBUTES) ")"
- AS_SIG(CLS_NAME_RCS_GET_RESPONSE));
-
- auto clsSetRequestHandler = env->FindClass(CLS_NAME_SET_REQUEST_HANDLER);
-
- g_method_SetRequestHandler_onSetRequested = env->GetMethodID(clsSetRequestHandler,
- "onSetRequested",
- "(" AS_SIG(CLS_NAME_RCS_REQUEST) AS_SIG(CLS_NAME_RESOURCEATTRIBUTES) ")"
- AS_SIG(CLS_NAME_RCS_SET_RESPONSE));
-
- auto clsOnAttributeUpdatedListener = env->FindClass(CLS_NAME_ON_ATTRIBUTE_UPDATESD_LISTENER);
-
- g_method_OnAttributeUpdatedListener_onAttributeUpdated = env->GetMethodID(
- clsOnAttributeUpdatedListener, "onAttributeUpdated",
- "(" AS_SIG(CLS_NAME_VALUE) AS_SIG(CLS_NAME_VALUE) ")V");
-
- auto clsAutoNotifyPolicy = env->FindClass(CLS_NAME_AUTO_NOTIFY_POLICY);
-
- g_obj_AutoNotifyPolicy_NEVER = env->NewGlobalRef(
- env->GetStaticObjectField(clsAutoNotifyPolicy, "NEVER",
- AS_SIG(CLS_NAME_AUTO_NOTIFY_POLICY)));
-
- g_obj_AutoNotifyPolicy_ALWAYS = env->NewGlobalRef(
- env->GetStaticObjectField(clsAutoNotifyPolicy, "ALWAYS",
- AS_SIG(CLS_NAME_AUTO_NOTIFY_POLICY)));
-
-
- g_obj_AutoNotifyPolicy_UPDATED = env->NewGlobalRef(
- env->GetStaticObjectField(clsAutoNotifyPolicy, "UPDATED",
- AS_SIG(CLS_NAME_AUTO_NOTIFY_POLICY)));
-
- auto clsSetRequestHandlerPolicy = env->FindClass(CLS_NAME_SET_REQUEST_HANDLER_POLICY);
-
- g_obj_SetRequestHandlerPolicy_NEVER = env->NewGlobalRef(
- env->GetStaticObjectField(clsSetRequestHandlerPolicy, "NEVER",
- AS_SIG(CLS_NAME_SET_REQUEST_HANDLER_POLICY)));
-
- g_obj_SetRequestHandlerPolicy_ACCEPT = env->NewGlobalRef(
- env->GetStaticObjectField(clsSetRequestHandlerPolicy, "ACCEPT",
- AS_SIG(CLS_NAME_SET_REQUEST_HANDLER_POLICY)));
-
- initRCSResponse(env);
-}
-
-void clearRCSResourceObject(JNIEnvWrapper* env)
-{
- env->DeleteGlobalRef(g_cls_RCSRequest);
-
- env->DeleteGlobalRef(g_obj_RCSSetResponse_AcceptanceMethod_DEFAULT);
- env->DeleteGlobalRef(g_obj_RCSSetResponse_AcceptanceMethod_ACCEPT);
- env->DeleteGlobalRef(g_obj_RCSSetResponse_AcceptanceMethod_IGNORE);
-
- env->DeleteGlobalRef(g_obj_AutoNotifyPolicy_NEVER);
- env->DeleteGlobalRef(g_obj_AutoNotifyPolicy_ALWAYS);
- env->DeleteGlobalRef(g_obj_AutoNotifyPolicy_UPDATED);
-
- env->DeleteGlobalRef(g_obj_SetRequestHandlerPolicy_NEVER);
- env->DeleteGlobalRef(g_obj_SetRequestHandlerPolicy_ACCEPT);
-}
-
-JNIEXPORT jint JNICALL
-Java_org_iotivity_service_server_RcsResponse_nativeGetDefaultErrorCode
-(JNIEnv*, jclass)
-{
- return RequestHandler::DEFAULT_ERROR_CODE;
-}
-
-JNIEXPORT jobject JNICALL
-Java_org_iotivity_service_server_RcsResourceObject_nativeBuild
-(JNIEnv* env, jclass, jstring uriObj, jstring typeObj, jstring interfaceObj, jboolean isObservable,
- jboolean isDiscoverable, jobject attrsObj)
-{
- LOGI("nativeBuild");
-
- EXPECT_RET_DEF(uriObj, "uri is null.");
-
- auto uri = toStdString(env, uriObj);
- auto type = toStdString(env, typeObj);
- auto interface = toStdString(env, interfaceObj);
-
- RCSResourceAttributes attrs;
- if (attrsObj)
- {
- attrs = toNativeAttributes(env, attrsObj);
- VERIFY_NO_EXC_RET_DEF(env);
- }
-
- try
- {
- auto resource = RCSResourceObject::Builder(uri, type,interface).
- setDiscoverable(isDiscoverable). setObservable(isObservable).setAttributes(attrs).
- build();
-
- auto resourceObj = env->NewObject(g_cls_RCSResourceObject, g_ctor_RCSResourceObject);
- VERIFY_NO_EXC_RET_DEF(env);
-
- setSafeNativeHandle< decltype(resource) >(env, resourceObj, resource);
-
- return resourceObj;
- }
- catch (const RCSPlatformException& e)
- {
- LOGE("%s", e.what());
- throwPlatformException(env, e);
- }
-
- return nullptr;
-}
-
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_server_RcsResourceObject_nativeSetAttribute
-(JNIEnv* env, jobject obj, jstring keyObj, jobject valueObj)
-{
- LOGD("nativeSetAttributeInteger");
-
- EXPECT(keyObj, "key is null.");
- EXPECT(valueObj, "value is null.");
-
- auto res = getResource(env, obj);
- VERIFY_NO_EXC(env);
-
- res->setAttribute(toStdString(env, keyObj), toNativeAttrsValue(env, valueObj));
-}
-
-JNIEXPORT jobject JNICALL
-Java_org_iotivity_service_server_RcsResourceObject_nativeGetAttributeValue
-(JNIEnv *env, jobject obj, jstring keyObj)
-{
- LOGD("nativeGetAttributeValue");
-
- EXPECT_RET_DEF(keyObj, "key is null.");
-
- auto res = getResource(env, obj);
- VERIFY_NO_EXC_RET_DEF(env);
-
- try
- {
- auto valueObj = newRCSValueObject(env, res->getAttributeValue(toStdString(env, keyObj)));
- VERIFY_NO_EXC_RET_DEF(env);
-
- return valueObj;
- }
- catch(const RCSInvalidKeyException& e)
- {
- return nullptr;
- }
-}
-
-JNIEXPORT jboolean JNICALL
-Java_org_iotivity_service_server_RcsResourceObject_nativeRemoveAttribute
-(JNIEnv* env, jobject obj, jstring keyObj)
-{
- LOGD("nativeRemoveAttribute");
-
- EXPECT_RET_DEF(keyObj, "key is null.");
-
- auto res = getResource(env, obj);
- VERIFY_NO_EXC_RET_DEF(env);
-
- return res->removeAttribute(toStdString(env, keyObj));
-}
-
-JNIEXPORT jboolean JNICALL
-Java_org_iotivity_service_server_RcsResourceObject_nativeContainsAttribute
-(JNIEnv* env, jobject obj, jstring keyObj)
-{
- LOGD("nativeContainsAttribute");
-
- EXPECT_RET_DEF(keyObj, "key is null.");
-
- auto res = getResource(env, obj);
- VERIFY_NO_EXC_RET_DEF(env);
-
- return res->containsAttribute(toStdString(env, keyObj));
-}
-
-JNIEXPORT jobject JNICALL
-Java_org_iotivity_service_server_RcsResourceObject_nativeGetAttributes
-(JNIEnv* env, jobject obj)
-{
- LOGD("nativeGetAttributes");
-
- auto res = getResource(env, obj);
- VERIFY_NO_EXC_RET_DEF(env);
-
- RCSResourceObject::LockGuard lock{ res, RCSResourceObject::AutoNotifyPolicy::NEVER };
- return newAttributesObject(env, res->getAttributes());
-}
-
-JNIEXPORT jboolean JNICALL
-Java_org_iotivity_service_server_RcsResourceObject_nativeIsObservable
-(JNIEnv* env, jobject obj)
-{
- LOGD("nativeIsObservable");
-
- auto res = getResource(env, obj);
- VERIFY_NO_EXC_RET_DEF(env);
-
- return res->isObservable();
-}
-
-JNIEXPORT jboolean JNICALL
-Java_org_iotivity_service_server_RcsResourceObject_nativeIsDiscoverable
-(JNIEnv *env, jobject obj)
-{
- LOGD("nativeIsDiscoverable");
-
- auto res = getResource(env, obj);
- VERIFY_NO_EXC_RET_DEF(env);
-
- return res->isDiscoverable();
-}
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_server_RcsResourceObject_nativeSetGetRequestHandler
-(JNIEnv *env, jobject obj, jobject listenerObj)
-{
- LOGD("nativeSetGetRequestHandler");
-
- auto res = getResource(env, obj);
- VERIFY_NO_EXC(env);
-
- if (listenerObj)
- {
- res->setGetRequestHandler(std::bind(onGetRequest, std::placeholders::_1, std::placeholders::_2,
- JavaGlobalRef{ env, listenerObj }));
- }
- else
- {
- res->setGetRequestHandler({ });
- }
-}
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_server_RcsResourceObject_nativeSetSetRequestHandler
-(JNIEnv* env, jobject obj, jobject listenerObj)
-{
- LOGD("nativeSetSetRequestHandler");
-
- auto res = getResource(env, obj);
- VERIFY_NO_EXC(env);
-
- if (listenerObj)
- {
- res->setSetRequestHandler(std::bind(onSetRequest, std::placeholders::_1,
- std::placeholders::_2, JavaGlobalRef{ env, listenerObj }));
- }
- else
- {
- res->setSetRequestHandler({ });
- }
-}
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_server_RcsResourceObject_nativeAddAttributeUpdatedListener
-(JNIEnv* env, jobject obj, jstring keyObj, jobject listenerObj)
-{
- LOGD("nativeAddAttributeUpdatedListener");
-
- auto res = getResource(env, obj);
- VERIFY_NO_EXC(env);
-
- auto key = toStdString(env, keyObj);
- VERIFY_NO_EXC(env);
-
- res->addAttributeUpdatedListener(std::move(key), std::bind(onAttributeUpdated,
- std::placeholders::_1, std::placeholders::_2, JavaGlobalRef{ env, listenerObj }));
-}
-
-JNIEXPORT jboolean JNICALL
-Java_org_iotivity_service_server_RcsResourceObject_nativeRemoveAttributeUpdatedListener
-(JNIEnv* env, jobject obj, jstring keyObj)
-{
- LOGD("nativeAddAttributeUpdatedListener");
-
- EXPECT_RET_DEF(keyObj, "key is null");
-
- auto res = getResource(env, obj);
- VERIFY_NO_EXC_RET_DEF(env);
-
- auto key = toStdString(env, keyObj);
- VERIFY_NO_EXC_RET_DEF(env);
-
- return res->removeAttributeUpdatedListener(key);
-}
-
-JNIEXPORT void JNICALL Java_org_iotivity_service_server_RcsResourceObject_nativeNotify
-(JNIEnv* env, jobject obj)
-{
- LOGD("nativeNotify");
-
- auto res = getResource(env, obj);
- VERIFY_NO_EXC(env);
-
- try
- {
- res->notify();
- }
- catch (const RCSPlatformException& e) {
- throwPlatformException(env, e);
- }
-}
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_server_RcsResourceObject_nativeSetAutoNotifyPolicy
-(JNIEnv* env, jobject obj, jobject policyObj)
-{
- LOGD("nativeSetAutoNotifyPolicy");
-
- EXPECT(policyObj, "policyObj is null");
-
- auto res = getResource(env, obj);
- VERIFY_NO_EXC(env);
-
- auto policy = convertAutoNotifyPolicy(env, policyObj);
- VERIFY_NO_EXC(env);
-
- res->setAutoNotifyPolicy(policy);
-}
-
-JNIEXPORT jobject JNICALL
-Java_org_iotivity_service_server_RcsResourceObject_nativeGetAutoNotifyPolicy
-(JNIEnv* env, jobject obj)
-{
- LOGD("nativeGetAutoNotifyPolicy");
-
- auto res = getResource(env, obj);
- VERIFY_NO_EXC_RET_DEF(env);
-
- return convertAutoNotifyPolicy(env, res->getAutoNotifyPolicy());
-}
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_server_RcsResourceObject_nativeSetSetRequestHandlerPolicy
-(JNIEnv* env, jobject obj, jobject policyObj)
-{
- LOGD("nativeSetSetRequestHandlerPolicy");
-
- EXPECT(policyObj, "policyObj is null");
-
- auto res = getResource(env, obj);
- VERIFY_NO_EXC(env);
-
- auto policy = convertSetRequestHandlerPolicy(env, policyObj);
- VERIFY_NO_EXC(env);
-
- res->setSetRequestHandlerPolicy(policy);
-}
-
-JNIEXPORT jobject JNICALL
-Java_org_iotivity_service_server_RcsResourceObject_nativeGetSetRequestHandlerPolicy
-(JNIEnv* env, jobject obj)
-{
- LOGD("nativeGetSetRequestHandlerPolicy");
-
- auto res = getResource(env, obj);
- VERIFY_NO_EXC_RET_DEF(env);
-
- return convertSetRequestHandlerPolicy(env, res->getSetRequestHandlerPolicy());
-}
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-#ifndef JNI_RCS_RESOURCE_OBJECT_H
-#define JNI_RCS_RESOURCE_OBJECT_H
-
-#include <jni.h>
-
-class JNIEnvWrapper;
-
-void initRCSResourceObject(JNIEnvWrapper*);
-void clearRCSResourceObject(JNIEnvWrapper*);
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-JNIEXPORT jint JNICALL
-Java_org_iotivity_service_server_RcsResponse_nativeGetDefaultErrorCode
-(JNIEnv*, jclass);
-
-JNIEXPORT jobject JNICALL
-Java_org_iotivity_service_server_RcsResourceObject_nativeBuild
-(JNIEnv*, jclass, jstring uri, jstring type, jstring interface, jboolean isObservable,
- jboolean isDiscovervable, jobject attrs);
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_server_RcsResourceObject_nativeSetAttribute
-(JNIEnv*, jobject, jstring key, jobject value);
-
-JNIEXPORT jobject JNICALL
-Java_org_iotivity_service_server_RcsResourceObject_nativeGetAttributeValue
-(JNIEnv*, jobject, jstring key);
-
-JNIEXPORT jboolean JNICALL
-Java_org_iotivity_service_server_RcsResourceObject_nativeRemoveAttribute
-(JNIEnv*, jobject, jstring key);
-
-JNIEXPORT jboolean JNICALL
-Java_org_iotivity_service_server_RcsResourceObject_nativeContainsAttribute
-(JNIEnv*, jobject, jstring key);
-
-JNIEXPORT jobject JNICALL
-Java_org_iotivity_service_server_RcsResourceObject_nativeGetAttributes
-(JNIEnv*, jobject);
-
-JNIEXPORT jboolean JNICALL
-Java_org_iotivity_service_server_RcsResourceObject_nativeIsObservable
-(JNIEnv*, jobject);
-
-JNIEXPORT jboolean JNICALL
-Java_org_iotivity_service_server_RcsResourceObject_nativeIsDiscoverable
-(JNIEnv*, jobject);
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_server_RcsResourceObject_nativeSetGetRequestHandler
-(JNIEnv*, jobject, jobject handler);
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_server_RcsResourceObject_nativeSetSetRequestHandler
-(JNIEnv*, jobject, jobject handler);
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_server_RcsResourceObject_nativeAddAttributeUpdatedListener
-(JNIEnv*, jobject, jstring key, jobject listenr);
-
-JNIEXPORT jboolean JNICALL
-Java_org_iotivity_service_server_RcsResourceObject_nativeRemoveAttributeUpdatedListener
-(JNIEnv*, jobject, jstring key);
-
-JNIEXPORT void JNICALL Java_org_iotivity_service_server_RcsResourceObject_nativeNotify
-(JNIEnv*, jobject);
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_server_RcsResourceObject_nativeSetAutoNotifyPolicy
-(JNIEnv*, jobject, jobject policyObj);
-
-JNIEXPORT jobject JNICALL
-Java_org_iotivity_service_server_RcsResourceObject_nativeGetAutoNotifyPolicy
-(JNIEnv*, jobject);
-
-JNIEXPORT void JNICALL
-Java_org_iotivity_service_server_RcsResourceObject_nativeSetSetRequestHandlerPolicy
-(JNIEnv*, jobject, jobject policyObj);
-
-JNIEXPORT jobject JNICALL
-Java_org_iotivity_service_server_RcsResourceObject_nativeGetSetRequestHandlerPolicy
-(JNIEnv*, jobject);
-
-#ifdef __cplusplus
-}
-#endif
-#endif // JNI_RCS_RESOURCE_OBJECT_H
-
-
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-#include "JniRcsValue.h"
-
-#include "JniRcsObject.h"
-#include "JniRcsResourceAttributes.h"
-#include "JavaClasses.h"
-#include "JavaExceptions.h"
-#include "JavaLocalRef.h"
-#include "Log.h"
-
-using namespace OIC::Service;
-
-#define LOG_TAG "JNI-RCSValue"
-
-#define CLS_NAME_VALUE_TYPE CLS_NAME_VALUE "$Type"
-#define CLS_NAME_VALUE_TYPEID CLS_NAME_VALUE "$TypeId"
-#define CLS_NAME_VALUE_NULL_TYPE CLS_NAME_VALUE "$NullType"
-
-namespace
-{
- jclass g_cls_RCSValue;
- jclass g_cls_Type;
- jclass g_cls_TypeId;
-
- jmethodID g_ctor_RCSValue;
-
- jmethodID g_smethod_Type_getDepth;
- jmethodID g_smethod_Type_getBaseTypeId;
-
- jmethodID g_method_RCSValue_getType;
-
- jfieldID g_field_RCSValue_mObject;
- jfieldID g_field_RCSValue_sNullValue;
-
- jobject g_obj_TypeId_Null;
- jobject g_obj_TypeId_Boolean;
- jobject g_obj_TypeId_Integer;
- jobject g_obj_TypeId_Double;
- jobject g_obj_TypeId_String;
- jobject g_obj_TypeId_ByteString;
- jobject g_obj_TypeId_Attributes;
- jobject g_obj_TypeId_Array;
-
- template< int >
- struct Int2Type{ };
-
- template< int DEPTH, typename BASE_TYPE >
- struct SeqType
- {
- typedef std::vector< typename SeqType< DEPTH - 1, BASE_TYPE >::type > type;
- };
-
- template< typename BASE_TYPE >
- struct SeqType< 0, BASE_TYPE >
- {
- typedef BASE_TYPE type;
- };
-
- template< typename T >
- struct BaseType
- {
- typedef T type;
- };
-
- template< typename T >
- struct BaseType< std::vector< T > >
- {
- typedef typename BaseType< T >::type type;
- };
-
-
- template< int D >
- struct ArrayPrefix
- {
- static constexpr char str[] = "";
- };
- template< int D >
- constexpr char ArrayPrefix< D >::str[];
-
- template<>
- struct ArrayPrefix< 1 >
- {
- static constexpr char str[] = "[";
- };
- constexpr char ArrayPrefix< 1 >::str[];
-
- template<>
- struct ArrayPrefix< 2 >
- {
- static constexpr char str[] = "[[";
- };
- constexpr char ArrayPrefix< 2 >::str[];
-
- struct PrimitiveType {
- static constexpr bool isPrimitive = true;
- };
-
- struct ObjectType {
- static constexpr bool isPrimitive = false;
- };
-
- template< typename T >
- struct JniTypeTrait;
-
- template<>
- struct JniTypeTrait< int >: public PrimitiveType
- {
- static_assert(sizeof(int) == sizeof(jint), "int and jint have different size!");
-
- static constexpr decltype(&JNIEnvWrapper::NewIntArray) newArrayFunc =
- &JNIEnvWrapper::NewIntArray;
- static constexpr decltype(&JNIEnvWrapper::SetIntArrayRegion) setArrayRegionFunc =
- &JNIEnvWrapper::SetIntArrayRegion;
-
- static constexpr decltype(&invoke_Integer_intValue<JNIEnvWrapper>) converter =
- &invoke_Integer_intValue<JNIEnvWrapper>;
-
- static constexpr decltype(&newIntegerObject<JNIEnvWrapper>) newObjectFunc =
- &newIntegerObject<JNIEnvWrapper>;
-
- static constexpr char className[] = "I";
- };
- constexpr char JniTypeTrait< int >::className[];
-
- template<>
- struct JniTypeTrait< bool >: public PrimitiveType
- {
- static_assert(sizeof(bool) == sizeof(jboolean), "bool and jboolean have different size!");
-
- static constexpr decltype(&JNIEnvWrapper::NewBooleanArray) newArrayFunc =
- &JNIEnvWrapper::NewBooleanArray;
- static constexpr decltype(&JNIEnvWrapper::SetBooleanArrayRegion) setArrayRegionFunc =
- &JNIEnvWrapper::SetBooleanArrayRegion;
-
- static constexpr decltype(&invoke_Boolean_booleanValue<JNIEnvWrapper>) converter =
- &invoke_Boolean_booleanValue<JNIEnvWrapper>;
-
- static constexpr decltype(&newBooleanObject<JNIEnvWrapper>) newObjectFunc =
- &newBooleanObject<JNIEnvWrapper>;
-
- static constexpr char className[] = "Z";
- };
- constexpr char JniTypeTrait< bool >::className[];
-
- template<>
- struct JniTypeTrait< double > : public PrimitiveType
- {
- static_assert(sizeof(double) == sizeof(jdouble), "double and jdouble have different size!");
-
- static constexpr decltype(&JNIEnvWrapper::NewDoubleArray) newArrayFunc =
- &JNIEnvWrapper::NewDoubleArray;
- static constexpr decltype(&JNIEnvWrapper::SetDoubleArrayRegion) setArrayRegionFunc =
- &JNIEnvWrapper::SetDoubleArrayRegion;
-
- static constexpr decltype(&invoke_Double_doubleValue<JNIEnvWrapper>) converter =
- &invoke_Double_doubleValue<JNIEnvWrapper>;
-
- static constexpr decltype(&newDoubleObject<JNIEnvWrapper>) newObjectFunc =
- &newDoubleObject<JNIEnvWrapper>;
-
- static constexpr char className[] = "D";
- };
- constexpr char JniTypeTrait< double >::className[];
-
- template<>
- struct JniTypeTrait< std::string >: public ObjectType
- {
- static constexpr decltype(&newStringObject<JNIEnvWrapper>) newObjectFunc =
- &newStringObject<JNIEnvWrapper>;
-
- static constexpr char className[] = "L" CLS_NAME_STRING ";";
- };
- constexpr char JniTypeTrait< std::string >::className[];
- template< typename ENV >
- inline RCSByteString invoke_ByteString_byteStringValue(JNIEnvWrapper *env, jobject byteStringObj)
- {
- EXPECT_RET(byteStringObj, "byteStringObj is null!", { });
-
- jclass g_cls_RCSByteString = env->FindClassAsGlobalRef(CLS_NAME_RESOURCEBYTESTRING);
-
- static jfieldID field_data = env->GetFieldID(g_cls_RCSByteString, "mData", "[B");
- static jfieldID field_length = env->GetFieldID(g_cls_RCSByteString, "mSize", "J");
-
- jbyteArray jDataInfo = (jbyteArray)env->GetObjectField(byteStringObj, field_data);
- jlong jDataLength = env->GetLongField(byteStringObj, field_length);
-
- jbyte *byteStringData = env->GetByteArrayElements(jDataInfo, NULL);
-
- RCSByteString byteString((uint8_t *)byteStringData, (size_t)jDataLength);
-
- env->ReleaseByteArrayElements(jDataInfo, (jbyte*) byteStringData, JNI_ABORT);
- env->DeleteGlobalRef(g_cls_RCSByteString);
-
- return byteString;
- }
-
- template< typename ENV >
- inline jobject newRCSByteStringObject(ENV* env, const RCSByteString& value)
- {
- jsize jSize = (jsize)value.size();
-
- jbyteArray jData = env->NewByteArray(jSize);
-
- std::vector<uint8_t> byteString = value.getByteString();
-
- env->SetByteArrayRegion(jData, 0, jSize, (const jbyte*)&byteString[0]);
-
- jclass g_cls_RCSByteString = env->FindClassAsGlobalRef(CLS_NAME_RESOURCEBYTESTRING);
- jmethodID g_ctor_RCSByteString = env->GetConstructorID(g_cls_RCSByteString, "([BJ)V");
-
- EXPECT_RET(g_ctor_RCSByteString, "g_ctor_RCSByteString is null!", { });
-
- jobject jObj = (jobject)env->NewObject(g_cls_RCSByteString, g_ctor_RCSByteString, jData,
- (jlong)jSize);
-
- EXPECT_RET(jObj, "jObj is null!", { });
-
- return jObj;
- }
-
- template<>
- struct JniTypeTrait< RCSByteString >: public ObjectType
- {
- static decltype(&invoke_ByteString_byteStringValue<JNIEnvWrapper>) converter;
-
- static decltype(&newRCSByteStringObject<JNIEnvWrapper>) newObjectFunc;
-
- static constexpr char className[] = CLS_NAME_RESOURCEBYTESTRING;
- };
- constexpr char JniTypeTrait< RCSByteString >::className[];
- decltype(&invoke_ByteString_byteStringValue<JNIEnvWrapper>) JniTypeTrait< RCSByteString >::converter =
- &invoke_ByteString_byteStringValue<JNIEnvWrapper>;
-
- decltype(&newRCSByteStringObject<JNIEnvWrapper>) JniTypeTrait< RCSByteString >::newObjectFunc =
- &newRCSByteStringObject<JNIEnvWrapper>;
-
- template<>
- struct JniTypeTrait< RCSResourceAttributes >: public ObjectType
- {
- inline static jobject newObjectFunc(JNIEnvWrapper* env, const RCSResourceAttributes& value)
- {
- return newAttributesObject(env, value);
- }
-
- inline static RCSResourceAttributes converter(JNIEnvWrapper* env, jobject obj)
- {
- return toNativeAttributes(env, obj);
- }
-
- static constexpr char className[] = "L" CLS_NAME_RESOURCEATTRIBUTES ";";
- };
- constexpr char JniTypeTrait< RCSResourceAttributes >::className[];
-
- inline void toNativeValue(JNIEnvWrapper* env, jobject obj, std::string& result, Int2Type< 0 >)
- {
- result = toStdString(env, static_cast< jstring >(obj));
- }
-
- template< typename T >
- inline void toNativeValue(JNIEnvWrapper* env, jobject obj, T& result, Int2Type< 0 >)
- {
- result = JniTypeTrait< T >::converter(env, obj);
- }
-
- template< int DEPTH, typename RET >
- inline void toNativeValue(JNIEnvWrapper* env, jobject obj, RET& result, Int2Type< DEPTH >)
- {
- const auto arrayObj = static_cast< jobjectArray >(obj);
- result.resize(env->GetArrayLength(arrayObj));
-
- for (typename RET::size_type i = 0; i < result.size(); ++i)
- {
- JavaLocalObject elementObj{ env, env->GetObjectArrayElement(arrayObj, i) };
-
- toNativeValue(env, elementObj, result[i], Int2Type< DEPTH - 1 >{ });
- }
- }
-
- template< typename T >
- inline typename std::enable_if< JniTypeTrait< T >::isPrimitive >::type
- toNativeValue(JNIEnvWrapper* env, jobject obj, std::vector< T >& result, Int2Type< 1 >)
- {
- const auto arrayObj = static_cast< jobjectArray >(obj);
- const jsize arraySize = env->GetArrayLength(arrayObj);
-
- T* raw = static_cast< T* >(env->GetPrimitiveArrayCritical(arrayObj, nullptr));
-
- try
- {
- result = std::vector< T >(raw, raw + arraySize);
- } catch (...)
- {
- }
-
- env->ReleasePrimitiveArrayCritical(arrayObj, raw, JNI_ABORT);
- }
-
- template< typename T >
- inline typename std::enable_if< !JniTypeTrait< T >::isPrimitive >::type
- toNativeValue(JNIEnvWrapper* env, jobject obj, std::vector< T >& result, Int2Type< 1 >)
- {
- const auto arrayObj = static_cast< jobjectArray >(obj);
- const jsize arraySize = env->GetArrayLength(arrayObj);
-
- result.resize(arraySize);
-
- for (typename std::vector< T >::size_type i = 0; i < result.size(); ++i)
- {
- JavaLocalObject elementObj{ env, env->GetObjectArrayElement(arrayObj, i) };
- toNativeValue(env, elementObj, result[i], Int2Type< 0 >{ });
- }
- }
-
-
- template< typename T, int DEPTH, typename RET = typename SeqType< DEPTH, T >::type >
- inline RET toNativeValue(JNIEnvWrapper* env, jobject obj)
- {
- static_assert(DEPTH >= 0, "DEPTH must be positive!");
-
- typename SeqType< DEPTH, T >::type result;
-
- toNativeValue(env, obj, result, Int2Type< DEPTH >{ });
-
- return result;
- }
-
- template< typename T >
- inline RCSResourceAttributes::Value toNativeValue(JNIEnvWrapper* env, jobject val, int depth)
- {
- switch (depth)
- {
- case 0: return toNativeValue< T, 0 >(env, val);
- case 1: return toNativeValue< T, 1 >(env, val);
- case 2: return toNativeValue< T, 2 >(env, val);
- case 3: return toNativeValue< T, 3 >(env, val);
- }
-
- return {};
- }
-
- inline RCSResourceAttributes::Value toNativeValue(JNIEnvWrapper* env, jobject val, int depth,
- RCSResourceAttributes::TypeId typeId)
- {
- LOGD("toNativeValue depth is %d", depth);
- EXPECT_RET(depth >= 0 && depth <= 3, "Unsupported depth!", {});
-
- switch (typeId)
- {
- case RCSResourceAttributes::TypeId::NULL_T: return { };
-
- case RCSResourceAttributes::TypeId::BOOL:
- return toNativeValue< bool >(env, val, depth);
-
- case RCSResourceAttributes::TypeId::INT:
- return toNativeValue< int >(env, val, depth);
-
- case RCSResourceAttributes::TypeId::DOUBLE:
- return toNativeValue< double >(env, val, depth);
-
- case RCSResourceAttributes::TypeId::STRING:
- return toNativeValue< std::string >(env, val, depth);
-
- case RCSResourceAttributes::TypeId::BYTESTRING:
- return toNativeValue< RCSByteString >(env, val, depth);
-
- case RCSResourceAttributes::TypeId::ATTRIBUTES:
- return toNativeValue< RCSResourceAttributes >(env, val, depth);
- }
-
- throwRCSException(env, "Failed to convert RCSValue : unknown type id");
- return {};
- }
-
- template< typename T, int DEPTH, typename BASE_TYPE = typename BaseType< T >::type >
- inline jobject createJavaObject(JNIEnvWrapper* env, const T& value, Int2Type< DEPTH >)
- {
- const std::string elementClsName{ std::string{ ArrayPrefix< DEPTH - 1 >::str }
- + JniTypeTrait< BASE_TYPE >::className };
-
- LOGD("create array %dd, %s", DEPTH, elementClsName.c_str());
-
- auto cls = env->FindClass(elementClsName.c_str());
-
- const jsize len = value.size();
-
- auto array = env->NewObjectArray(len, cls, nullptr);
-
- for(jsize i = 0; i < len; ++i)
- {
- auto element = createJavaObject(env, value[i], Int2Type< DEPTH - 1>{ });
- env->SetObjectArrayElement(array, i, element);
- }
-
- return array;
- }
-
- template< typename T, typename TRAIT = JniTypeTrait< T > >
- inline typename std::enable_if< TRAIT::isPrimitive, jobject >::type
- createJavaObject(JNIEnvWrapper* env, const std::vector< T >& value, Int2Type< 1 >)
- {
- LOGD("create array with newArray");
- const jsize len = value.size();
-
- auto array = (env->*TRAIT::newArrayFunc)(len);
-
- if (!value.empty()) (env->*TRAIT::setArrayRegionFunc)(array, 0, len, &value[0]);
-
- return array;
- }
-
- inline jobject createJavaObject(JNIEnvWrapper* env, const std::vector< bool >& value, Int2Type< 1 >)
- {
- const auto len = value.size();
- LOGD("create bool array with newArray %d", len);
-
- auto arrayObj = env->NewBooleanArray(len);
-
- bool* raw = static_cast< bool* >(env->GetPrimitiveArrayCritical(arrayObj, 0));
-
- std::copy(value.begin(), value.end(), raw);
-
- env->ReleasePrimitiveArrayCritical(arrayObj, raw, 0);
-
- return arrayObj;
- }
-
- template< typename T, typename TRAIT = JniTypeTrait< T > >
- inline jobject createJavaObject(JNIEnvWrapper* env, const T& value, Int2Type< 0 >)
- {
- LOGD("createJavaObject 0-depth");
- return TRAIT::newObjectFunc(env, value);
- }
-
- template< int DEPTH >
- inline jobject createJavaObject(JNIEnvWrapper* env, const RCSResourceAttributes::Value& value)
- {
- const auto type = value.getType();
- const auto baseType = RCSResourceAttributes::Type::getBaseTypeId(type);
-
- LOGD("createJavaObject with DEPTH. type is %d", static_cast< int >(baseType));
-
- switch (baseType)
- {
- case RCSResourceAttributes::TypeId::NULL_T:
- return env->GetStaticObjectField(g_cls_RCSValue, g_field_RCSValue_sNullValue);
-
- case RCSResourceAttributes::TypeId::BOOL:
- return createJavaObject(env, value.get< typename SeqType< DEPTH, bool >::type >(),
- Int2Type< DEPTH >{ });
-
- case RCSResourceAttributes::TypeId::INT:
- return createJavaObject(env, value.get< typename SeqType< DEPTH, int >::type >(),
- Int2Type< DEPTH >{ });
-
- case RCSResourceAttributes::TypeId::DOUBLE:
- return createJavaObject(env, value.get< typename SeqType< DEPTH, double >::type >(),
- Int2Type< DEPTH >{ });
-
- case RCSResourceAttributes::TypeId::STRING:
- return createJavaObject(env,
- value.get< typename SeqType< DEPTH, std::string >::type >(),
- Int2Type< DEPTH >{ });
-
- case RCSResourceAttributes::TypeId::BYTESTRING:
- return createJavaObject(env,
- value.get< typename SeqType< DEPTH, RCSByteString >::type >(),
- Int2Type< DEPTH > { });
-
- case RCSResourceAttributes::TypeId::ATTRIBUTES:
- return createJavaObject(env,
- value.get< typename SeqType< DEPTH, RCSResourceAttributes >::type >(),
- Int2Type< DEPTH >{ });
- }
-
- LOGE("Unknown type!");
-
- return nullptr;
- }
-
- inline jobject createJavaObject(JNIEnvWrapper* env, const RCSResourceAttributes::Value& value)
- {
- const auto type = value.getType();
- const auto depth = RCSResourceAttributes::Type::getDepth(type);
-
- EXPECT_RET(depth >= 0 && depth <= 3, "Unsupported depth!", {});
-
- switch (depth)
- {
- case 0: return createJavaObject< 0 >(env, value);
- case 1: return createJavaObject< 1 >(env, value);
- case 2: return createJavaObject< 2 >(env, value);
- case 3: return createJavaObject< 3 >(env, value);
- }
-
- return nullptr;
- }
-
- inline RCSResourceAttributes::TypeId toNativeTypeId(JNIEnvWrapper* env, jobject typeIdObj)
- {
- typedef RCSResourceAttributes::TypeId TypeId;
-
- if (env->IsSameObject(g_obj_TypeId_Null, typeIdObj)) return TypeId::NULL_T;
- if (env->IsSameObject(g_obj_TypeId_Boolean, typeIdObj)) return TypeId::BOOL;
- if (env->IsSameObject(g_obj_TypeId_Integer, typeIdObj)) return TypeId::INT;
- if (env->IsSameObject(g_obj_TypeId_Double, typeIdObj)) return TypeId::DOUBLE;
- if (env->IsSameObject(g_obj_TypeId_String, typeIdObj)) return TypeId::STRING;
- if (env->IsSameObject(g_obj_TypeId_ByteString, typeIdObj)) return TypeId::BYTESTRING;
- if (env->IsSameObject(g_obj_TypeId_Attributes, typeIdObj)) return TypeId::ATTRIBUTES;
- if (env->IsSameObject(g_obj_TypeId_Array, typeIdObj)) return TypeId::VECTOR;
-
- throwRCSException(env, "Failed to convert RCSValue : unknown type id");
- return TypeId::NULL_T;
- }
-
- jobject getTypeIdObj(JNIEnvWrapper* env, const char* name)
- {
- return env->NewGlobalRef(
- env->GetStaticObjectField(g_cls_TypeId, name, AS_SIG(CLS_NAME_VALUE_TYPEID)));
- }
-}
-
-void initRCSValue(JNIEnvWrapper* env)
-{
- g_cls_RCSValue = env->FindClassAsGlobalRef(CLS_NAME_VALUE);
- g_ctor_RCSValue = env->GetConstructorID(g_cls_RCSValue, "(" AS_SIG(CLS_NAME_OBJECT) ")V");
-
- g_method_RCSValue_getType = env->GetMethodID(g_cls_RCSValue, "getType",
- "()" AS_SIG(CLS_NAME_VALUE_TYPE));
-
- g_field_RCSValue_mObject = env->GetFieldID(g_cls_RCSValue, "mObject", AS_SIG(CLS_NAME_OBJECT));
-
- g_field_RCSValue_sNullValue = env->GetStaticFieldID(g_cls_RCSValue, "sNullValue",
- AS_SIG(CLS_NAME_VALUE_NULL_TYPE));
-
- g_cls_Type = env->FindClassAsGlobalRef(CLS_NAME_VALUE_TYPE);
-
- g_smethod_Type_getBaseTypeId = env->GetStaticMethodID(g_cls_Type, "getBaseTypeId",
- "(" AS_SIG(CLS_NAME_VALUE_TYPE) ")" AS_SIG(CLS_NAME_VALUE_TYPEID));
-
- g_smethod_Type_getDepth = env->GetStaticMethodID(g_cls_Type, "getDepth",
- "(" AS_SIG(CLS_NAME_VALUE_TYPE) ")I");
-
- g_cls_TypeId = env->FindClassAsGlobalRef(CLS_NAME_VALUE_TYPEID);
-
- g_obj_TypeId_Null = getTypeIdObj(env, "NULL");
- g_obj_TypeId_Boolean = getTypeIdObj(env, "BOOLEAN");
- g_obj_TypeId_Integer = getTypeIdObj(env, "INTEGER");
- g_obj_TypeId_Double = getTypeIdObj(env, "DOUBLE");
- g_obj_TypeId_String = getTypeIdObj(env, "STRING");
- g_obj_TypeId_ByteString = getTypeIdObj(env, "BYTESTRING");
- g_obj_TypeId_Attributes = getTypeIdObj(env, "ATTRIBUTES");
- g_obj_TypeId_Array = getTypeIdObj(env, "ARRAY");
-}
-
-void clearRCSValue(JNIEnvWrapper* env)
-{
- env->DeleteGlobalRef(g_cls_RCSValue);
- env->DeleteGlobalRef(g_cls_Type);
- env->DeleteGlobalRef(g_cls_TypeId);
-
- env->DeleteGlobalRef(g_obj_TypeId_Null);
- env->DeleteGlobalRef(g_obj_TypeId_Boolean);
- env->DeleteGlobalRef(g_obj_TypeId_Integer);
- env->DeleteGlobalRef(g_obj_TypeId_Double);
- env->DeleteGlobalRef(g_obj_TypeId_String);
- env->DeleteGlobalRef(g_obj_TypeId_ByteString);
- env->DeleteGlobalRef(g_obj_TypeId_Attributes);
- env->DeleteGlobalRef(g_obj_TypeId_Array);
-}
-
-RCSResourceAttributes::Value toNativeAttrsValue(JNIEnv* env, jobject valueObj)
-{
- JNIEnvWrapper envWrapper(env);
-
- try
- {
- return toNativeAttrsValue(&envWrapper, valueObj);
- }
- catch (const JavaException&)
- {
- return { };
- }
-}
-
-RCSResourceAttributes::Value toNativeAttrsValue(JNIEnvWrapper* env, jobject valueObj)
-{
- auto typeObj = env->CallObjectMethod(valueObj, g_method_RCSValue_getType);
- auto typeIdObj = env->CallStaticObjectMethod(g_cls_Type, g_smethod_Type_getBaseTypeId, typeObj);
- auto depth = env->CallStaticIntMethod(g_cls_Type, g_smethod_Type_getDepth, typeObj);
- auto memObj = env->GetObjectField(valueObj, g_field_RCSValue_mObject);
-
- auto ret = toNativeValue(env, memObj, depth, toNativeTypeId(env, typeIdObj));
-
- if (env->get()->ExceptionCheck()) throw JavaException();
-
- return ret;
-}
-
-jobject newRCSValueObject(JNIEnv* env, const RCSResourceAttributes::Value& value)
-{
- JNIEnvWrapper envWrapper(env);
-
- try
- {
- return newRCSValueObject(&envWrapper, value);
- }
- catch (const JavaException&)
- {
- return {};
- }
-}
-
-jobject newRCSValueObject(JNIEnvWrapper* env, const RCSResourceAttributes::Value& value)
-{
- LOGD("newRCSValueObject");
-
- JavaLocalObject valueObj{ env, createJavaObject(env, value) };
-
- if (env->get()->ExceptionCheck()) throw JavaException();
-
- return env->NewObject(g_cls_RCSValue, g_ctor_RCSValue, valueObj.get());
-}
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-#ifndef JNI_RCS_VALUE_H_
-#define JNI_RCS_VALUE_H_
-
-#include <jni.h>
-
-#include "RCSResourceAttributes.h"
-
-class JNIEnvWrapper;
-
-void initRCSValue(JNIEnvWrapper*);
-void clearRCSValue(JNIEnvWrapper*);
-
-OIC::Service::RCSResourceAttributes::Value toNativeAttrsValue(JNIEnv*, jobject);
-OIC::Service::RCSResourceAttributes::Value toNativeAttrsValue(JNIEnvWrapper*, jobject);
-
-jobject newRCSValueObject(JNIEnv*, const OIC::Service::RCSResourceAttributes::Value&);
-jobject newRCSValueObject(JNIEnvWrapper*, const OIC::Service::RCSResourceAttributes::Value&);
-
-#endif // JNI_RCS_VALUE_H_
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-#ifndef RCS_JNI_ENV_WRAPPER_H_
-#define RCS_JNI_ENV_WRAPPER_H_
-
-#include <jni.h>
-
-#include <exception>
-
-#include "JavaLocalRef.h"
-
-class JavaException: public std::exception
-{
-};
-
-class JNIEnvWrapper
-{
-public:
- JNIEnvWrapper() noexcept : m_env{ } {}
- JNIEnvWrapper(JNIEnv* env) noexcept : m_env{ env } {}
-
- JNIEnvWrapper& operator=(JNIEnv* env) noexcept
- {
- m_env = env;
- return *this;
- }
-
- jboolean IsSameObject(jobject lhs, jobject rhs)
- {
- return m_env->IsSameObject(lhs, rhs);
- }
-
- jclass GetObjectClass(jobject obj)
- {
- auto ret = m_env->GetObjectClass(obj);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- jclass FindClass(const char* name)
- {
- auto ret = m_env->FindClass(name);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- jclass FindClassAsGlobalRef(const char* name)
- {
- JavaLocalClass cls{ m_env, FindClass(name) };
-
- return NewGlobalRef(cls);
- }
-
- jobject NewGlobalRef(jobject obj)
- {
- auto ret = m_env->NewGlobalRef(obj);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- template<typename T>
- T NewGlobalRef(T obj)
- {
- auto ret = static_cast< T >(m_env->NewGlobalRef(obj));
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- template<typename T>
- T NewGlobalRef(const JavaLocalRef< T >& obj)
- {
- auto ret = static_cast< T >(m_env->NewGlobalRef(obj));
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- void DeleteGlobalRef(jobject obj)
- {
- m_env->DeleteGlobalRef(obj);
- }
-
- jobject NewObject(jclass cls, jmethodID ctor, ...)
- {
- va_list args;
- va_start(args, ctor);
- auto ret = m_env->NewObjectV(cls, ctor,args);
- va_end(args);
-
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- jstring NewStringUTF(const char* str)
- {
- auto ret = m_env->NewStringUTF(str);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- const char* GetStringUTFChars(jstring str, jboolean* isCopy)
- {
- auto ret = m_env->GetStringUTFChars(str, isCopy);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- void ReleaseStringUTFChars(jstring str, const char* chars)
- {
- m_env->ReleaseStringUTFChars(str, chars);
- if (m_env->ExceptionCheck()) throw JavaException();
- }
-
- jmethodID GetConstructorID(jclass cls, const char* sig)
- {
- auto ret = m_env->GetMethodID(cls, "<init>", sig);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- jmethodID GetMethodID(jclass cls, const char* name, const char* sig)
- {
- auto ret = m_env->GetMethodID(cls, name, sig);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- jmethodID GetStaticMethodID(jclass cls, const char* name, const char* sig)
- {
- auto ret = m_env->GetStaticMethodID(cls, name, sig);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
-
- jfieldID GetFieldID(jclass cls, const char* name, const char* sig)
- {
- auto ret = m_env->GetFieldID(cls, name, sig);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- jfieldID GetStaticFieldID(jclass cls, const char* name, const char* sig)
- {
- auto ret = m_env->GetStaticFieldID(cls, name, sig);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- jobject GetStaticObjectField(jclass cls, jfieldID fieldId)
- {
- auto ret = m_env->GetStaticObjectField(cls, fieldId);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- jobject GetStaticObjectField(jclass cls, const char* name, const char* sig)
- {
- return GetStaticObjectField(cls, GetStaticFieldID(cls, name, sig));
- }
-
- jint GetIntField(jobject obj, jfieldID fieldId)
- {
- auto ret = m_env->GetIntField(obj, fieldId);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- jlong GetLongField(jobject obj, jfieldID fieldId)
- {
- auto ret = m_env->GetLongField(obj, fieldId);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- void SetLongField(jobject obj, jfieldID fieldId, jlong val)
- {
- m_env->SetLongField(obj, fieldId, val);
- if (m_env->ExceptionCheck()) throw JavaException();
- }
-
- jobject GetObjectField(jobject obj, jfieldID fieldId)
- {
- auto ret = m_env->GetObjectField(obj, fieldId);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- jint CallStaticIntMethod(jclass cls, jmethodID methodId, ...)
- {
- va_list args;
- va_start(args, methodId);
- auto ret = m_env->CallStaticIntMethodV(cls, methodId, args);
- va_end(args);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- jobject CallStaticObjectMethod(jclass cls, jmethodID methodId, ...)
- {
- va_list args;
- va_start(args, methodId);
- auto ret = m_env->CallStaticObjectMethodV(cls, methodId, args);
- va_end(args);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- void CallVoidMethod(jobject obj, jmethodID methodId, ...)
- {
- va_list args;
- va_start(args, methodId);
- m_env->CallVoidMethodV(obj, methodId, args);
- va_end(args);
- if (m_env->ExceptionCheck()) throw JavaException();
- }
-
- jboolean CallBooleanMethod(jobject obj, jmethodID methodId, ...)
- {
- va_list args;
- va_start(args, methodId);
- auto ret = m_env->CallBooleanMethodV(obj, methodId, args);
- va_end(args);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- jint CallIntMethod(jobject obj, jmethodID methodId, ...)
- {
- va_list args;
- va_start(args, methodId);
- auto ret = m_env->CallIntMethod(obj, methodId, args);
- va_end(args);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- jdouble CallDoubleMethod(jobject obj, jmethodID methodId, ...)
- {
- va_list args;
- va_start(args ,methodId);
- auto ret = m_env->CallDoubleMethod(obj, methodId, args);
- va_end(args);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
-
- jobject CallObjectMethod(jobject obj, jmethodID methodId, ...)
- {
- va_list args;
- va_start(args, methodId);
- auto ret = m_env->CallObjectMethodV(obj, methodId, args);
- va_end(args);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- jbooleanArray NewBooleanArray(jsize len)
- {
- auto ret = m_env->NewBooleanArray(len);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- jintArray NewIntArray(jsize len)
- {
- auto ret = m_env->NewIntArray(len);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- jdoubleArray NewDoubleArray(jsize len)
- {
- auto ret = m_env->NewDoubleArray(len);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- jbyteArray NewByteArray(jsize len)
- {
- auto ret = m_env->NewByteArray(len);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- jobjectArray NewObjectArray(jsize len, jclass cls, jobject init)
- {
- auto ret = m_env->NewObjectArray(len, cls, init);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- jsize GetArrayLength(jarray array)
- {
- auto ret = m_env->GetArrayLength(array);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- jobject GetObjectArrayElement(jobjectArray array, jsize index)
- {
- auto ret = m_env->GetObjectArrayElement(array, index);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- jbyte *GetByteArrayElements(jbyteArray array, jboolean *value)
- {
- auto ret = m_env->GetByteArrayElements(array, value);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- void SetObjectArrayElement(jobjectArray array, jsize index, jobject val)
- {
- m_env->SetObjectArrayElement(array, index, val);
- if (m_env->ExceptionCheck()) throw JavaException();
- }
-
- void SetBooleanArrayRegion(jbooleanArray array, jsize start, jsize len, const jboolean* buf)
- {
- m_env->SetBooleanArrayRegion(array, start, len, buf);
- if (m_env->ExceptionCheck()) throw JavaException();
- }
-
- void SetIntArrayRegion(jintArray array, jsize start, jsize len, const jint* buf)
- {
- m_env->SetIntArrayRegion(array, start, len, buf);
- if (m_env->ExceptionCheck()) throw JavaException();
- }
-
- void SetDoubleArrayRegion(jdoubleArray array, jsize start, jsize len, const jdouble* buf)
- {
- m_env->SetDoubleArrayRegion(array, start, len, buf);
- if (m_env->ExceptionCheck()) throw JavaException();
- }
-
- void SetByteArrayRegion(jbyteArray array, jsize start, jsize len, const jbyte *buf)
- {
- m_env->SetByteArrayRegion(array, start, len, buf);
- if (m_env->ExceptionCheck()) throw JavaException();
- }
-
- void* GetPrimitiveArrayCritical(jarray array, jboolean* isCopy)
- {
- auto ret = m_env->GetPrimitiveArrayCritical(array, isCopy);
- if (m_env->ExceptionCheck()) throw JavaException();
- return ret;
- }
-
- void ReleasePrimitiveArrayCritical(jarray array, void* carray, int mode)
- {
- m_env->ReleasePrimitiveArrayCritical(array, carray, mode);
- if (m_env->ExceptionCheck()) throw JavaException();
- }
-
- void ReleaseByteArrayElements(jbyteArray array, jbyte* byteArray, int mode)
- {
- m_env->ReleaseByteArrayElements(array, byteArray, mode);
- if (m_env->ExceptionCheck()) throw JavaException();
- }
-
- void ThrowNew(jclass cls, const char* msg)
- {
- m_env->ThrowNew(cls, msg);
- throw JavaException();
- }
-
- void ExceptionDescribe() const noexcept
- {
- m_env->ExceptionDescribe();
- }
-
- void ExceptionClear() noexcept
- {
- m_env->ExceptionClear();
- }
-
- jboolean ExceptionCheck() const noexcept
- {
- return m_env->ExceptionCheck();
- }
-
- operator bool() const noexcept
- {
- return m_env != nullptr;
- }
-
- JNIEnv* get() const
- {
- return m_env;
- }
-
-private:
- JNIEnv* m_env;
-};
-
-
-
-#endif // RCS_JNI_ENV_WRAPPER_H_
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-#include "JavaClasses.h"
-
-#include "JNIEnvWrapper.h"
-
-jclass g_cls_String;
-jclass g_cls_Integer;
-jclass g_cls_Double;
-jclass g_cls_Boolean;
-
-jclass g_cls_ArrayList;
-jclass g_cls_Set;
-jclass g_cls_Map;
-jclass g_cls_MapEntry;
-jclass g_cls_Iterator;
-
-jmethodID g_method_Boolean_booleanValue;
-jmethodID g_method_Integer_intValue;
-jmethodID g_method_Double_doubleValue;
-
-jmethodID g_method_Collection_add;
-
-jmethodID g_method_Set_iterator;
-
-jmethodID g_method_Map_entrySet;
-jmethodID g_method_Map_put;
-
-jmethodID g_method_MapEntry_getKey;
-jmethodID g_method_MapEntry_getValue;
-
-jmethodID g_method_Iterator_hasNext;
-jmethodID g_method_Iterator_next;
-
-jmethodID g_ctor_Boolean;
-jmethodID g_ctor_Integer;
-jmethodID g_ctor_Double;
-
-jmethodID g_ctor_ArrayList;
-
-namespace
-{
- inline void initPrimitiveTypes(JNIEnvWrapper* env)
- {
- g_cls_Boolean = env->FindClassAsGlobalRef(CLS_NAME_BOOLEAN);
- g_ctor_Boolean = env->GetConstructorID(g_cls_Boolean, "(Z)V");
- g_method_Boolean_booleanValue = env->GetMethodID(g_cls_Boolean, "booleanValue", "()Z");
-
- g_cls_Integer = env->FindClassAsGlobalRef(CLS_NAME_INTEGER);
- g_ctor_Integer = env->GetConstructorID(g_cls_Integer, "(I)V");
- g_method_Integer_intValue = env->GetMethodID(g_cls_Integer, "intValue", "()I");
-
- g_cls_Double = env->FindClassAsGlobalRef(CLS_NAME_DOUBLE);
- g_ctor_Double = env->GetConstructorID(g_cls_Double, "(D)V");
- g_method_Double_doubleValue = env->GetMethodID(g_cls_Double, "doubleValue", "()D");
-
- g_cls_String = env->FindClassAsGlobalRef(CLS_NAME_STRING);
- }
-}
-
-void initJavaClasses(JNIEnvWrapper* env)
-{
- initPrimitiveTypes(env);
-
- auto clsCollection = env->FindClass(CLS_NAME_COLLECTION);
- g_method_Collection_add = env->GetMethodID(clsCollection, "add",
- "(" AS_SIG(CLS_NAME_OBJECT) ")Z");
-
- g_cls_ArrayList = env->FindClassAsGlobalRef(CLS_NAME_ARRAY_LIST);
- g_ctor_ArrayList = env->GetConstructorID(g_cls_ArrayList, "()V");
-
- g_cls_Set = env->FindClassAsGlobalRef(CLS_NAME_SET);
- g_method_Set_iterator = env->GetMethodID(g_cls_Set, "iterator", "()" AS_SIG(CLS_NAME_ITERATOR));
-
- g_cls_Map = env->FindClassAsGlobalRef(CLS_NAME_MAP);
- g_method_Map_entrySet = env->GetMethodID(g_cls_Map, "entrySet", "()" AS_SIG(CLS_NAME_SET));
- g_method_Map_put = env->GetMethodID(g_cls_Map, "put",
- "(" AS_SIG(CLS_NAME_OBJECT) AS_SIG(CLS_NAME_OBJECT) ")" AS_SIG(CLS_NAME_OBJECT));
-
- g_cls_MapEntry = env->FindClassAsGlobalRef(CLS_NAME_MAP_ENTRY);
- g_method_MapEntry_getKey = env->GetMethodID(g_cls_MapEntry, "getKey",
- "()" AS_SIG(CLS_NAME_OBJECT));
- g_method_MapEntry_getValue = env->GetMethodID(g_cls_MapEntry, "getValue",
- "()" AS_SIG(CLS_NAME_OBJECT));
-
- g_cls_Iterator = env->FindClassAsGlobalRef(CLS_NAME_ITERATOR);
- g_method_Iterator_hasNext = env->GetMethodID(g_cls_Iterator, "hasNext", "()Z");
- g_method_Iterator_next = env->GetMethodID(g_cls_Iterator, "next", "()" AS_SIG(CLS_NAME_OBJECT));
-}
-
-void clearJavaClasses(JNIEnvWrapper* env)
-{
- env->DeleteGlobalRef(g_cls_Boolean);
- env->DeleteGlobalRef(g_cls_Integer);
- env->DeleteGlobalRef(g_cls_Double);
- env->DeleteGlobalRef(g_cls_String);
- env->DeleteGlobalRef(g_cls_Set);
- env->DeleteGlobalRef(g_cls_Map);
- env->DeleteGlobalRef(g_cls_MapEntry);
- env->DeleteGlobalRef(g_cls_Iterator);
-}
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-#ifndef JAVA_CLASSES_H_
-#define JAVA_CLASSES_H_
-
-#include <jni.h>
-
-#include <string>
-
-#define PACKAGE_NAME "org/iotivity/service"
-
-#define CLS_NAME_VALUE PACKAGE_NAME "/RcsValue"
-
-#define CLS_NAME_RESOURCEATTRIBUTES PACKAGE_NAME "/RcsResourceAttributes"
-#define CLS_NAME_REMOTERESOURCEOBJECT PACKAGE_NAME "/client/RcsRemoteResourceObject"
-#define CLS_NAME_RESOURCEBYTESTRING PACKAGE_NAME "/RcsByteString"
-
-#define CLS_NAME_OBJECT "java/lang/Object"
-#define CLS_NAME_STRING "java/lang/String"
-#define CLS_NAME_INTEGER "java/lang/Integer"
-#define CLS_NAME_DOUBLE "java/lang/Double"
-#define CLS_NAME_BOOLEAN "java/lang/Boolean"
-
-#define CLS_NAME_COLLECTION "java/util/Collection"
-#define CLS_NAME_ARRAY_LIST "java/util/ArrayList"
-#define CLS_NAME_SET "java/util/Set"
-#define CLS_NAME_MAP "java/util/Map"
-#define CLS_NAME_MAP_ENTRY "java/util/Map$Entry"
-#define CLS_NAME_ITERATOR "java/util/Iterator"
-
-#define EXC_NAME_RCS PACKAGE_NAME "/RcsException"
-#define EXC_NAME_PLATFORM PACKAGE_NAME "/RcsPlatformException"
-#define EXC_NAME_ILLEGAL_STATE PACKAGE_NAME "/RcsIllegalStateException"
-
-#define AS_SIG(CLS_NAME) "L" CLS_NAME ";"
-
-class JNIEnvWrapper;
-
-extern jclass g_cls_Integer;
-extern jclass g_cls_Double;
-extern jclass g_cls_Boolean;
-extern jclass g_cls_String;
-
-extern jclass g_cls_ArrayList;
-extern jclass g_cls_Set;
-extern jclass g_cls_Map;
-extern jclass g_cls_MapEntry;
-extern jclass g_cls_Iterator;
-
-extern jmethodID g_method_Boolean_booleanValue;
-extern jmethodID g_method_Integer_intValue;
-extern jmethodID g_method_Double_doubleValue;
-
-extern jmethodID g_method_Collection_add;
-
-extern jmethodID g_method_Set_iterator;
-
-extern jmethodID g_method_Map_entrySet;
-extern jmethodID g_method_Map_put;
-
-extern jmethodID g_method_MapEntry_getKey;
-extern jmethodID g_method_MapEntry_getValue;
-
-extern jmethodID g_method_Iterator_hasNext;
-extern jmethodID g_method_Iterator_next;
-
-extern jmethodID g_ctor_Boolean;
-extern jmethodID g_ctor_Integer;
-extern jmethodID g_ctor_Double;
-
-extern jmethodID g_ctor_ArrayList;
-
-void initJavaClasses(JNIEnvWrapper*);
-void clearJavaClasses(JNIEnvWrapper*);
-
-template< typename ENV >
-inline jobject newBooleanObject(ENV* env, bool value)
-{
- return env->NewObject(g_cls_Boolean, g_ctor_Boolean, value);
-}
-
-template< typename ENV >
-inline jobject newIntegerObject(ENV* env, int value)
-{
- return env->NewObject(g_cls_Integer, g_ctor_Integer, value);
-}
-
-template< typename ENV >
-inline jobject newDoubleObject(ENV* env, double value)
-{
- return env->NewObject(g_cls_Double, g_ctor_Double, value);
-}
-
-template< typename ENV >
-inline jstring newStringObject(ENV* env, const std::string& value)
-{
- return env->NewStringUTF(value.c_str());
-}
-
-template< typename ENV >
-inline jstring newStringObjectCstr(ENV* env, const char* value)
-{
- return env->NewStringUTF(value);
-}
-
-template< typename ENV >
-inline std::string toStdString(ENV* env, jstring obj)
-{
- if (!obj) return "";
-
- auto cstr = env->GetStringUTFChars(obj, nullptr);
-
- if (!cstr) return "";
-
- std::string result{ cstr };
-
- env->ReleaseStringUTFChars(obj, cstr);
-
- return result;
-}
-
-template< typename ENV >
-inline jobject newArrayList(ENV* env)
-{
- return env->NewObject(g_cls_ArrayList, g_ctor_ArrayList);
-}
-
-template< typename ENV >
-inline bool invoke_Boolean_booleanValue(ENV* env, jobject obj)
-{
- return env->CallBooleanMethod(obj, g_method_Boolean_booleanValue);
-}
-
-template< typename ENV >
-inline int invoke_Integer_intValue(ENV* env, jobject obj)
-{
- return env->CallIntMethod(obj, g_method_Integer_intValue);
-}
-
-template< typename ENV >
-inline double invoke_Double_doubleValue(ENV* env, jobject obj)
-{
- return env->CallDoubleMethod(obj, g_method_Double_doubleValue);
-}
-
-template< typename ENV >
-inline jboolean invoke_Collection_add(ENV* env, jobject collectionObj, jobject valueObj)
-{
- return env->CallBooleanMethod(collectionObj, g_method_Collection_add, valueObj);
-}
-
-template< typename ENV >
-inline jobject invoke_Map_entrySet(ENV* env, jobject mapObj)
-{
- return env->CallObjectMethod(mapObj, g_method_Map_entrySet);
-}
-
-template< typename ENV >
-inline jobject invoke_Map_put(ENV* env, jobject mapObj, jobject keyObj, jobject valueObj)
-{
- return env->CallObjectMethod(mapObj, g_method_Map_put, keyObj, valueObj);
-}
-
-template< typename ENV >
-inline jobject invoke_MapEntry_getKey(ENV* env, jobject entryObj)
-{
- return env->CallObjectMethod(entryObj, g_method_MapEntry_getKey);
-}
-
-template< typename ENV >
-inline jobject invoke_MapEntry_getValue(ENV* env, jobject entryObj)
-{
- return env->CallObjectMethod(entryObj, g_method_MapEntry_getValue);
-}
-
-template< typename ENV >
-inline jobject invoke_Set_iterator(ENV* env, jobject setObj)
-{
- return env->CallObjectMethod(setObj, g_method_Set_iterator);
-}
-
-template< typename ENV >
-inline bool invoke_Iterator_hasNext(ENV* env, jobject iterObj)
-{
- return env->CallBooleanMethod(iterObj, g_method_Iterator_hasNext);
-}
-
-template< typename ENV >
-inline jobject invoke_Iterator_next(ENV* env, jobject iterObj)
-{
- return env->CallObjectMethod(iterObj, g_method_Iterator_next);
-}
-
-#endif // JAVA_CLASSES_H_
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-#include "JavaExceptions.h"
-
-#include "JNIEnvWrapper.h"
-#include "Verify.h"
-
-#include "RCSException.h"
-
-namespace
-{
- jclass g_cls_PlatformException;
-
- jmethodID g_ctor_PlatformException;
-}
-
-void initJavaExceptions(JNIEnvWrapper* env)
-{
- g_cls_PlatformException = env->FindClassAsGlobalRef(EXC_NAME_PLATFORM);
- g_ctor_PlatformException = env->GetConstructorID(g_cls_PlatformException,
- "(" AS_SIG(CLS_NAME_STRING) "I)V");
-}
-
-void clearJavaExceptions(JNIEnvWrapper* env)
-{
- env->DeleteGlobalRef(g_cls_PlatformException);
-}
-
-void throwPlatformException(JNIEnv* env, const OIC::Service::RCSPlatformException& e)
-{
- auto msg = newStringObject(env, e.getReason());
- VERIFY_NO_EXC(env);
-
- auto exObj = env->NewObject(g_cls_PlatformException, g_ctor_PlatformException,
- msg, e.getReasonCode());
- VERIFY_NO_EXC(env);
-
- env->Throw(static_cast< jthrowable >(exObj));
-}
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-#ifndef JAVA_EXCEPTIONS_H_
-#define JAVA_EXCEPTIONS_H_
-
-#include <jni.h>
-
-#include "JavaClasses.h"
-
-namespace OIC
-{
- namespace Service
- {
- class RCSPlatformException;
- }
-}
-
-class JNIEnvWrapper;
-
-void initJavaExceptions(JNIEnvWrapper*);
-void clearJavaExceptions(JNIEnvWrapper*);
-
-void throwPlatformException(JNIEnv*, const OIC::Service::RCSPlatformException&);
-
-template < typename ENV >
-void throwRCSException(ENV* env, const char* msg)
-{
- env->ThrowNew(env->FindClass(EXC_NAME_RCS), msg);
-}
-
-
-#endif // JAVA_EXCEPTIONS_H_
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-#ifndef JAVA_GLOBAL_REF_H_
-#define JAVA_GLOBAL_REF_H_
-
-#include <memory>
-#include <cassert>
-
-#include "ScopedEnv.h"
-
-class JavaGlobalRef
-{
-public:
- JavaGlobalRef(JNIEnv* env, jobject obj) noexcept :
- m_obj{ }
- {
- assert(env && "JNIEnv is nullptr");
-
- static auto deleter = [](jobject* obj)
- {
- if (obj && *obj)
- {
- ScopedEnv env;
- env->DeleteGlobalRef(*obj);
- }
- delete obj;
- };
-
- m_obj.reset(new jobject{ env->NewGlobalRef(obj) }, deleter);
- }
-
- operator jobject() const noexcept
- {
- return *m_obj;
- }
-
-private:
- std::shared_ptr< jobject > m_obj;
-};
-
-
-
-#endif // JAVA_GLOBAL_REF_H_
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-#ifndef JAVA_LOCAL_REF_H_
-#define JAVA_LOCAL_REF_H_
-
-#include <jni.h>
-#include <cassert>
-
-template < typename T >
-class JavaLocalRef
-{
-public:
- JavaLocalRef(JNIEnv* env, T obj) noexcept :
- m_env{ env },
- m_obj{ obj }
- {
- assert(env && "JNIEnv is nullptr");
- }
-
- template< typename ENV >
- JavaLocalRef(ENV* env, T obj) noexcept :
- m_env{ env->get() },
- m_obj{ obj }
- {
- assert(env && "JNIEnv is nullptr");
- }
-
- ~JavaLocalRef()
- {
- if (m_obj) m_env->DeleteLocalRef(m_obj);
- }
-
- operator bool() const noexcept { return m_obj; }
- operator T() const noexcept { return m_obj; }
-
- jobject get() const noexcept { return m_obj; }
-
- JavaLocalRef(const JavaLocalRef&) = delete;
- JavaLocalRef& operator=(const JavaLocalRef&) = delete;
-
- JavaLocalRef& operator=(JavaLocalRef&&) = delete;
-
-private:
- JNIEnv* m_env;
- T m_obj;
-};
-
-typedef JavaLocalRef< jobject > JavaLocalObject;
-typedef JavaLocalRef< jstring > JavaLocalString;
-typedef JavaLocalRef< jclass > JavaLocalClass;
-
-#endif // JAVA_LOCAL_REF_H_
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-#ifndef RCS_JNI_LOG_H
-#define RCS_JNI_LOG_H
-
-#include <android/log.h>
-
-#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
-#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
-#define LOGW(...) __android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__)
-#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
-
-#define LOGT_I(LOG_TAG, ...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
-#define LOGT_D(LOG_TAG, ...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
-#define LOGT_E(LOG_TAG, ...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
-
-#define EXPECT(EXP, MSG) do { if (!(EXP)) { LOGW(MSG); return; } } while(false)
-
-#define EXPECT_RET(EXP, MSG, RET_IF_FAILED) \
- do { if (!(EXP)) { LOGW(MSG); return RET_IF_FAILED; } } while(false)
-
-#define EXPECT_RET_DEF(EXP, MSG) EXPECT_RET(EXP, MSG, { })
-
-#endif // RCS_JNI_LOG_H
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-#ifndef RCS_JIN_SCOPEDENV_H_
-#define RCS_JIN_SCOPEDENV_H_
-
-#include <utility>
-
-#include <jni.h>
-
-#include "JNIEnvWrapper.h"
-#include "Log.h"
-
-extern JavaVM* g_jvm;
-
-namespace Detail
-{
- inline std::pair<JNIEnv*, bool> getEnv()
- {
- JNIEnv* env{ };
- bool needToDetach{ };
-
- auto ret = g_jvm->GetEnv((void**) &env, JNI_VERSION_1_6);
-
- switch (ret)
- {
- case JNI_OK:
- break;
-
- case JNI_EDETACHED:
- {
- auto attachRet = g_jvm->AttachCurrentThread(&env, NULL);
-
- if (attachRet != JNI_OK)
- {
- LOGT_E("JNI-ScopedEnv", "Failed to get the environment : %d", attachRet);
- }
- else
- {
- needToDetach = true;
- }
- break;
- }
- case JNI_EVERSION:
- LOGT_E("JNI-ScopedEnv", "JNI version not supported");
- break;
-
- default:
- LOGT_E("JNI-ScopedEnv", "Failed to get the environment");
- break;
- }
-
- return { env, needToDetach };
- }
-}
-
-class ScopedEnv
-{
-public:
- ScopedEnv() noexcept :
- m_env { },
- m_needToDetach{ false }
- {
- auto val = Detail::getEnv();
-
- m_env = val.first;
- m_needToDetach = val.second;
- }
-
- ~ScopedEnv()
- {
- if (m_env && m_needToDetach)
- {
- g_jvm->DetachCurrentThread();
- }
- }
-
- ScopedEnv(const ScopedEnv&) = delete;
- ScopedEnv& operator=(const ScopedEnv&) = delete;
-
- operator bool() const noexcept
- {
- return m_env;
- }
-
- JNIEnv* operator->() noexcept
- {
- return m_env;
- }
-
- JNIEnv* get() noexcept
- {
- return m_env;
- }
-
-private:
- JNIEnv* m_env;
- bool m_needToDetach;
-};
-
-class ScopedEnvWrapper
-{
-public:
- ScopedEnvWrapper() noexcept :
- m_env { },
- m_needToDetach{ false }
- {
- auto val = Detail::getEnv();
-
- m_env = val.first;
- m_needToDetach = val.second;
- }
-
- ~ScopedEnvWrapper()
- {
- if (m_env && m_needToDetach)
- {
- g_jvm->DetachCurrentThread();
- }
- }
-
- ScopedEnvWrapper(const ScopedEnvWrapper&) = delete;
- ScopedEnvWrapper& operator=(const ScopedEnvWrapper&) = delete;
-
- operator bool() const noexcept
- {
- return m_env;
- }
-
- JNIEnvWrapper* operator->() noexcept
- {
- return &m_env;
- }
-
- JNIEnvWrapper* get() noexcept
- {
- return &m_env;
- }
-
-private:
- JNIEnvWrapper m_env;
- bool m_needToDetach;
-};
-
-#endif // RCS_JIN_SCOPEDENV_H_
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-#ifndef RCS_JNI_VERIFY_H_
-#define RCS_JNI_VERIFY_H_
-
-#define VERIFY_NO_EXC(ENV) do { \
- if ((ENV)->ExceptionCheck()) { (ENV)->ExceptionDescribe(); return; } } while(false)
-
-#define VERIFY_NO_EXC_RET(ENV, RET) do { \
- if ((ENV)->ExceptionCheck()) { (ENV)->ExceptionDescribe(); return RET; } } while(false)
-
-#define VERIFY_NO_EXC_RET_DEF(ENV) VERIFY_NO_EXC_RET(ENV, { })
-
-#endif // RCS_JNI_VERIFY_H_
+++ /dev/null
-/*
- *******************************************************************
- *
- * Copyright 2015 Intel Corporation.
- *
- *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- *
- * 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 ':service'
+++ /dev/null
-.gradle
-/local.properties
-/.idea
-.DS_Store
-/build
-/captures
-/gradle
+++ /dev/null
-To build the app
-
-1. build Iotivity with TARGET_OS=android
-
-2. Copy aar files into app/libs folder
- - {Iotivity_root}/android/android_api/base/build/outputs/aar/iotivity-{TARGET_ARCH}-base-{MODE}.aar
- - {Iotivity_root}/service/resource-encapsulation/android/service/build/outputs/aar/iotivity-{TARGET_ARCH}-service-{MODE}.aar
-
-3. Configure dependencies for libs in app/build.gradle
- - default TARGET_ARCH is armeabi
- - default MODE is release
-
- for example, if you build Iotivity as follows,
-
- $scons TARGET_OS=android TARGET_ARCH=x86 RELEASE=0
-
- then, dependencies should be modified like below
-
- dependencies {
- compile(name:'iotivity-x86-service-debug', ext:'aar')
- compile(name:'iotivity-x86-base-debug', ext:'aar')
- }
-
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<module external.linked.project.id="RESampleClientApp" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$" external.system.id="GRADLE" external.system.module.group="" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
- <component name="FacetManager">
- <facet type="java-gradle" name="Java-Gradle">
- <configuration>
- <option name="BUILD_FOLDER_PATH" value="$MODULE_DIR$/build" />
- <option name="BUILDABLE" value="false" />
- </configuration>
- </facet>
- </component>
- <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_7" inherit-compiler-output="true">
- <exclude-output />
- <content url="file://$MODULE_DIR$">
- <excludeFolder url="file://$MODULE_DIR$/.gradle" />
- </content>
- <orderEntry type="inheritedJdk" />
- <orderEntry type="sourceFolder" forTests="false" />
- </component>
-</module>
\ No newline at end of file
+++ /dev/null
-/build
-/libs/*
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<module external.linked.project.id=":app" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$/.." external.system.id="GRADLE" external.system.module.group="RESampleClientApp" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
- <component name="FacetManager">
- <facet type="android-gradle" name="Android-Gradle">
- <configuration>
- <option name="GRADLE_PROJECT_PATH" value=":app" />
- </configuration>
- </facet>
- <facet type="android" name="Android">
- <configuration>
- <option name="SELECTED_BUILD_VARIANT" value="debug" />
- <option name="SELECTED_TEST_ARTIFACT" value="_android_test_" />
- <option name="ASSEMBLE_TASK_NAME" value="assembleDebug" />
- <option name="COMPILE_JAVA_TASK_NAME" value="compileDebugSources" />
- <option name="ASSEMBLE_TEST_TASK_NAME" value="assembleDebugAndroidTest" />
- <option name="COMPILE_JAVA_TEST_TASK_NAME" value="compileDebugAndroidTestSources" />
- <afterSyncTasks>
- <task>generateDebugAndroidTestSources</task>
- <task>generateDebugSources</task>
- </afterSyncTasks>
- <option name="ALLOW_USER_CONFIGURATION" value="false" />
- <option name="MANIFEST_FILE_RELATIVE_PATH" value="/src/main/AndroidManifest.xml" />
- <option name="RES_FOLDER_RELATIVE_PATH" value="/src/main/res" />
- <option name="RES_FOLDERS_RELATIVE_PATH" value="file://$MODULE_DIR$/src/main/res" />
- <option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" />
- </configuration>
- </facet>
- </component>
- <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_7" inherit-compiler-output="false">
- <output url="file://$MODULE_DIR$/build/intermediates/classes/debug" />
- <output-test url="file://$MODULE_DIR$/build/intermediates/classes/androidTest/debug" />
- <exclude-output />
- <content url="file://$MODULE_DIR$">
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/debug" isTestSource="false" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/debug" isTestSource="false" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/debug" isTestSource="false" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/debug" isTestSource="false" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/debug" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/resValues/debug" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/androidTest/debug" isTestSource="true" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/androidTest/debug" isTestSource="true" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/androidTest/debug" isTestSource="true" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/androidTest/debug" isTestSource="true" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/androidTest/debug" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/resValues/androidTest/debug" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/res" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/resources" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/assets" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/aidl" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/java" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/jni" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/rs" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/res" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/assets" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/aidl" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/jni" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/rs" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/res" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/resources" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/assets" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/aidl" isTestSource="true" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/java" isTestSource="true" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/jni" isTestSource="true" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/rs" isTestSource="true" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/assets" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/bundles" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/classes" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/coverage-instrumented-classes" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dependency-cache" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex-cache" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/exploded-aar/iotivity-armeabi-base-release/jars" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/exploded-aar/iotivity-armeabi-service-release/jars" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/jacoco" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/javaResources" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/libs" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/lint" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/manifests" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/ndk" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/pre-dexed" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/proguard" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/res" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/rs" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/symbols" />
- <excludeFolder url="file://$MODULE_DIR$/build/outputs" />
- <excludeFolder url="file://$MODULE_DIR$/build/tmp" />
- </content>
- <orderEntry type="jdk" jdkName="Android API 21 Platform" jdkType="Android SDK" />
- <orderEntry type="sourceFolder" forTests="false" />
- <orderEntry type="library" exported="" name="iotivity-armeabi-base-release-" level="project" />
- <orderEntry type="library" exported="" name="iotivity-armeabi-service-release-" level="project" />
- </component>
-</module>
\ No newline at end of file
+++ /dev/null
-apply plugin: 'com.android.application'
-
-android {
- compileSdkVersion 21
- buildToolsVersion "20.0.0"
-
- defaultConfig {
- applicationId "org.iotivity.service.sample.client"
- minSdkVersion 21
- targetSdkVersion 21
- versionCode 1
- versionName "1.0"
- }
- buildTypes {
- release {
- minifyEnabled false
- proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
- }
- }
-}
-
-dependencies {
- compile fileTree(dir: 'libs', include: ['*.jar'])
-
- compile(name:'iotivity-armeabi-service-release', ext:'aar')
- compile(name:'iotivity-base-armeabi-release', ext:'aar')
-}
+++ /dev/null
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="org.iotivity.service.sample.client">
-
- <uses-permission android:name="android.permission.INTERNET" />
- <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
-
- <application android:allowBackup="true" android:label="@string/app_name"
- android:icon="@mipmap/ic_launcher" android:theme="@style/AppTheme">
- <activity
- android:name=".MainActivity"
- android:label="@string/app_name" >
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
-
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
- <activity android:name=".ResourceClientActivity" />
- </application>
-
-</manifest>
+++ /dev/null
-/******************************************************************
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- * <p>
- * <p>
- * <p>
- * 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
- * <p>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p>
- * 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.iotivity.service.sample.client;
-
-import android.app.Activity;
-import android.app.AlertDialog;
-import android.content.DialogInterface;
-import android.content.DialogInterface.OnClickListener;
-import android.content.Intent;
-import android.net.ConnectivityManager;
-import android.net.NetworkInfo;
-import android.os.Bundle;
-import android.util.Log;
-import android.view.View;
-import android.widget.AdapterView;
-import android.widget.AdapterView.OnItemClickListener;
-import android.widget.ArrayAdapter;
-import android.widget.ListView;
-
-import org.iotivity.base.ModeType;
-import org.iotivity.base.OcPlatform;
-import org.iotivity.base.PlatformConfig;
-import org.iotivity.base.QualityOfService;
-import org.iotivity.base.ServiceType;
-
-import java.util.ArrayList;
-
-
-/**
- * Starting Activity of the application responsible for configuring the
- * OcPlatform and redirecting to ResourceClient activity.
- */
-public class MainActivity extends Activity {
-
- private static final String LOG_TAG = MainActivity.class.getSimpleName();
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
-
- if (!isWifiConnected()) {
- showWifiUnavailableDialog();
- return;
- }
-
- configurePlatform();
- }
-
- public void onResourceClientClick(View v) {
- startActivity(new Intent(this, ResourceClientActivity.class));
- }
-
- private boolean isWifiConnected() {
- ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
- return connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected();
- }
-
- private void showWifiUnavailableDialog() {
- new AlertDialog.Builder(this).setTitle("Error")
- .setMessage("WiFi is not enabled/connected! Please connect the WiFi and start application again...")
- .setCancelable(false)
- .setPositiveButton("OK", new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- finish();
- }
- }).create().show();
- }
-
- private void configurePlatform() {
- OcPlatform.Configure(new PlatformConfig(getApplicationContext(),
- ServiceType.IN_PROC, ModeType.CLIENT_SERVER, "0.0.0.0", 0,
- QualityOfService.LOW));
-
- Log.i(LOG_TAG, "Configuration done Successfully");
- }
-}
+++ /dev/null
-/******************************************************************
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- * <p>
- * <p>
- * <p>
- * 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
- * <p>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p>
- * 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.iotivity.service.sample.client;
-
-import static org.iotivity.service.client.RcsRemoteResourceObject.OnCacheUpdatedListener;
-import static org.iotivity.service.client.RcsRemoteResourceObject.OnStateChangedListener;
-import static org.iotivity.service.client.RcsRemoteResourceObject.ResourceState;
-
-import java.lang.ref.WeakReference;
-
-import org.iotivity.service.RcsException;
-import org.iotivity.service.RcsResourceAttributes;
-import org.iotivity.service.RcsValue;
-import org.iotivity.service.client.RcsAddress;
-import org.iotivity.service.client.RcsDiscoveryManager;
-import org.iotivity.service.client.RcsDiscoveryManager.OnResourceDiscoveredListener;
-import org.iotivity.service.client.RcsRemoteResourceObject;
-import org.iotivity.service.client.RcsRemoteResourceObject.OnRemoteAttributesReceivedListener;
-
-import android.app.Activity;
-import android.app.AlertDialog;
-import android.content.DialogInterface;
-import android.os.Bundle;
-import android.os.Handler;
-import android.os.Message;
-import android.util.Log;
-import android.view.View;
-import android.widget.AdapterView;
-import android.widget.AdapterView.OnItemClickListener;
-import android.widget.ArrayAdapter;
-import android.widget.Button;
-import android.widget.EditText;
-import android.widget.ListView;
-import android.widget.TextView;
-import android.widget.Toast;
-
-/*
- * Activity for handling user's selection on UI for Resource Client APIs.
- * & for updating UI.
- */
-public class ResourceClientActivity extends Activity
- implements OnItemClickListener {
-
- private static final String LOG_TAG = ResourceClientActivity.class
- .getSimpleName();
-
- private static final int MSG_ID_RESOURCE_DISCOVERED = 0;
- private static final int MSG_ID_ATTRIBUTE_RECEIVED = 1;
- private static final int MSG_ID_PRINT_LOG = 2;
-
- private static final String RESOURCE_TYPE = "oic.r.temperature.sensor";
- private static final String ATTR_KEY_TEMPERATURE = "Temperature";
-
- private TextView mLogView;
- private ListView mListView;
- private Button mDiscoveryBtn;
-
- private Handler mHandler;
- private ArrayAdapter<Item> mItemAdapter;
-
- private RcsDiscoveryManager.DiscoveryTask mDiscoveryTask;
- private RcsRemoteResourceObject mResourceObj;
-
- private OnResourceDiscoveredListener mOnResourceDiscoveredListener = new OnResourceDiscoveredListener() {
-
- @Override
- public void onResourceDiscovered(
- RcsRemoteResourceObject foundResource) {
- Log.i(LOG_TAG, "onResourceDiscovered");
-
- mHandler.obtainMessage(MSG_ID_RESOURCE_DISCOVERED, foundResource)
- .sendToTarget();
- }
- };
-
- private OnStateChangedListener mOnStateChangedListener = new OnStateChangedListener() {
-
- @Override
- public void onStateChanged(ResourceState resourceState) {
- Log.i(LOG_TAG, "onStateChanged");
-
- mHandler.obtainMessage(MSG_ID_PRINT_LOG,
- "Current Resource State : " + resourceState);
- }
- };
-
- private OnRemoteAttributesReceivedListener mOnRemoteAttributesReceivedListener = new OnRemoteAttributesReceivedListener() {
- @Override
- public void onAttributesReceived(RcsResourceAttributes attrs,
- int eCode) {
- Log.i(LOG_TAG, "onAttributesReceived");
-
- mHandler.obtainMessage(MSG_ID_ATTRIBUTE_RECEIVED, attrs)
- .sendToTarget();
- }
- };
-
- private OnCacheUpdatedListener mOnCacheUpdatedListener = new OnCacheUpdatedListener() {
- @Override
- public void onCacheUpdated(RcsResourceAttributes attrs) {
- Log.i(LOG_TAG, "onCacheUpdated");
-
- mHandler.obtainMessage(MSG_ID_ATTRIBUTE_RECEIVED, attrs)
- .sendToTarget();
- }
- };
-
- private Item mStartMonitoring = new Item("1. Start Monitoring") {
- @Override
- public void execute() throws RcsException {
- if (mResourceObj.isMonitoring()) {
- printLog("Monitoring already started");
- return;
- }
-
- mResourceObj.startMonitoring(mOnStateChangedListener);
-
- if (mResourceObj.isMonitoring()) {
- printLog("Monitoring started successfully");
- }
- }
- };
-
- private Item mStopMonitoring = new Item("2. Stop Monitoring") {
- @Override
- public void execute() throws RcsException {
- if (mResourceObj.isMonitoring()) {
-
- mResourceObj.stopMonitoring();
-
- if (!mResourceObj.isMonitoring()) {
- printLog("Monitoring stopped successfully");
- }
-
- } else {
- printLog("Monitoring not started");
- }
- }
- };
-
- private Item mGetRemoteAttributes = new Item("3. Get Remote Attributes") {
- @Override
- public void execute() throws RcsException {
- mResourceObj
- .getRemoteAttributes(mOnRemoteAttributesReceivedListener);
- }
- };
-
- private Item mSetRemoteAttributes = new Item("4. Set Remote Attributes") {
-
- @Override
- public void execute() throws RcsException {
- showInputValueDialog();
- }
- };
-
- private Item mStartCaching = new Item("5. Start Caching") {
- @Override
- public void execute() throws RcsException {
- if (mResourceObj.isCaching()) {
- printLog("Caching already started");
- return;
- }
-
- mResourceObj.startCaching(mOnCacheUpdatedListener);
-
- if (mResourceObj.isCaching()) {
- printLog("Caching started successfully");
- }
-
- }
- };
-
- private Item mGetCacheState = new Item("6. Get Cache State") {
- @Override
- public void execute() throws RcsException {
- printLog("Cache State : " + mResourceObj.getCacheState());
- }
- };
-
- private Item mGetCachedAttributes = new Item(
- "7. Get All Cached Attributes") {
- @Override
- public void execute() throws RcsException {
- printAttributes(mResourceObj.getCachedAttributes());
- }
- };
-
- private Item mGetCachedAttribute = new Item("8. Get Cached Attribute") {
- @Override
- public void execute() throws RcsException {
- printLog(ATTR_KEY_TEMPERATURE + " : " + mResourceObj
- .getCachedAttribute(ATTR_KEY_TEMPERATURE).asInt());
- }
- };
-
- private Item mStopCaching = new Item("9. Stop Caching") {
- @Override
- public void execute() throws RcsException {
- if (mResourceObj.isCaching()) {
-
- mResourceObj.stopCaching();
-
- if (!mResourceObj.isCaching()) {
- printLog("Caching stopped successfully");
- } else {
- printLog("Stopping caching unsuccessful");
- }
-
- } else {
- printLog("Caching not started");
- }
- }
-
- };
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_resource_client);
-
- mListView = (ListView) findViewById(R.id.list_menu);
- mLogView = (TextView) findViewById(R.id.text_log);
- mDiscoveryBtn = (Button) findViewById(R.id.btn_discovery);
-
- mHandler = new ClientHandler(this);
-
- initMenuList();
- }
-
- @Override
- protected void onDestroy() {
- super.onDestroy();
-
- if (mDiscoveryTask != null) mDiscoveryTask.cancel();
- if (mResourceObj != null) mResourceObj.destroy();
- }
-
- private void initMenuList() {
- Item[] items = new Item[] { mStartMonitoring, mStopMonitoring,
- mGetRemoteAttributes, mSetRemoteAttributes, mStartCaching,
- mGetCacheState, mGetCachedAttributes, mGetCachedAttribute,
- mStopCaching };
-
- mItemAdapter = new ArrayAdapter<>(this,
- android.R.layout.simple_list_item_1, items);
-
- mListView.setAdapter(mItemAdapter);
-
- mListView.setOnItemClickListener(this);
- }
-
- @Override
- public void onItemClick(AdapterView<?> parent, View view, int position,
- long id) {
- if (mResourceObj == null) {
- showError("no discovered RemoteResourceObject");
- return;
- }
-
- try {
- mItemAdapter.getItem(position).execute();
- } catch (RcsException e) {
- showError(e);
- }
- }
-
- public void onDiscoverResourceClick(View v) {
- toggleDiscovery();
- }
-
- private void toggleDiscovery() {
- if (mDiscoveryTask == null) {
- try {
- mDiscoveryTask = RcsDiscoveryManager.getInstance()
- .discoverResourceByType(RcsAddress.multicast(), RESOURCE_TYPE,
- mOnResourceDiscoveredListener);
- mDiscoveryBtn.setText(R.string.cancel_discovery);
-
- mListView.setVisibility(View.INVISIBLE);
-
- if (mResourceObj != null) {
- mResourceObj.destroy();
- mResourceObj = null;
- }
- } catch (RcsException e) {
- showError(e);
- }
- } else {
- mDiscoveryTask.cancel();
- mDiscoveryTask = null;
-
- mDiscoveryBtn.setText(R.string.discover_resource);
- }
- }
-
- private void printAttributes(RcsResourceAttributes attributes) {
- try {
- StringBuilder sb = new StringBuilder();
- for (String key : attributes.keySet()) {
- sb.append(key + " : " + attributes.get(key));
- }
- printLog(sb.toString());
- } catch (Exception e) {
- printLog(e);
- }
- }
-
- private void setRemoteResourceObject(
- RcsRemoteResourceObject foundResource) {
- if (mResourceObj != null) {
- Log.w(LOG_TAG, "Another remote resource found...");
- return;
- }
-
- mResourceObj = foundResource;
-
- mListView.setVisibility(View.VISIBLE);
- toggleDiscovery();
-
- try {
- printLog(resourceInfo(mResourceObj));
- } catch (RcsException e) {
- showError(e);
- }
- }
-
- private void showInputValueDialog() {
- final AlertDialog dialog = new AlertDialog.Builder(this)
- .setTitle("Enter the Temperature Value")
- .setView(R.layout.dialog_content_edit_text)
- .setNegativeButton("Cancel", null).create();
-
- dialog.setButton(DialogInterface.BUTTON_POSITIVE, "OK",
- new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialogInterface,
- int which) {
-
- EditText temperatureValue = (EditText) dialog
- .findViewById(R.id.attributeValue);
-
- try {
- RcsValue value = new RcsValue(Integer.parseInt(
- temperatureValue.getText().toString()));
-
- RcsResourceAttributes attrs = new RcsResourceAttributes();
- attrs.put(ATTR_KEY_TEMPERATURE, value);
-
- mResourceObj.setRemoteAttributes(attrs,
- mOnRemoteAttributesReceivedListener);
- } catch (NumberFormatException e) {
- showError("Please enter the Integer Value");
- } catch (RcsException e) {
- showError(e);
- }
- }
- });
- dialog.show();
- }
-
- private void showError(String msg) {
- Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
- Log.e(LOG_TAG, msg);
- }
-
- private void showError(Exception e) {
- Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
- Log.e(LOG_TAG, e.getMessage(), e);
- }
-
- private void printLog(String message) {
- Log.i(LOG_TAG, message);
- mLogView.setText(message);
- }
-
- private void printLog(Exception e) {
- Log.i(LOG_TAG, e.getMessage(), e);
- mLogView.setText(e.getMessage());
- }
-
- private String resourceInfo(RcsRemoteResourceObject resourceObject)
- throws RcsException {
- StringBuilder sb = new StringBuilder();
-
- sb.append("URI : " + resourceObject.getUri() + "\n");
- sb.append("Host : " + resourceObject.getAddress() + "\n");
- for (String type : resourceObject.getTypes()) {
- sb.append("resourceType : " + type + "\n");
- }
-
- for (String itf : resourceObject.getInterfaces()) {
- sb.append("resourceInterfaces : " + itf + "\n");
- }
-
- sb.append("isObservable : " + resourceObject.isObservable() + "\n");
-
- return sb.toString();
- }
-
- private static abstract class Item {
- private final String mTitle;
-
- protected Item(String title) {
- mTitle = title;
- }
-
- @Override
- public String toString() {
- return mTitle;
- }
-
- public abstract void execute() throws RcsException;
- }
-
- private static class ClientHandler extends Handler {
- private WeakReference<ResourceClientActivity> mActivityRef;
-
- private ClientHandler(ResourceClientActivity activity) {
- mActivityRef = new WeakReference<>(activity);
- }
-
- @Override
- public void handleMessage(Message msg) {
- super.handleMessage(msg);
-
- ResourceClientActivity activity = mActivityRef.get();
- if (activity == null) return;
-
- switch (msg.what) {
- case MSG_ID_RESOURCE_DISCOVERED:
- activity.setRemoteResourceObject(
- (RcsRemoteResourceObject) msg.obj);
- break;
-
- case MSG_ID_ATTRIBUTE_RECEIVED:
- activity.printAttributes((RcsResourceAttributes) msg.obj);
- break;
-
- case MSG_ID_PRINT_LOG:
- activity.printLog(msg.obj.toString());
- break;
- }
- }
- }
-}
+++ /dev/null
-<?xml version="1.0" encoding="utf-8"?>
-
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical">
-
- <Button
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:onClick="onResourceClientClick"
- android:text="@string/resource_client" />
-
-</LinearLayout>
+++ /dev/null
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical">
-
- <Button
- android:id="@+id/btn_discovery"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_alignParentTop="true"
- android:onClick="onDiscoverResourceClick"
- android:text="@string/discover_resource" />
-
- <ListView
- android:id="@+id/list_menu"
- android:layout_width="match_parent"
- android:layout_height="0dp"
- android:layout_weight="1"
- android:visibility="invisible" />
-
- <TextView
- android:id="@+id/text_log"
- android:layout_width="fill_parent"
- android:layout_height="150dp"
- android:layout_marginLeft="10dp"
- android:layout_marginTop="10dp"
- android:ems="10" />
-</LinearLayout>
+++ /dev/null
-<?xml version="1.0" encoding="utf-8"?>
-<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical">
-
- <EditText
- android:id="@+id/attributeValue"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentTop="true"
- android:layout_centerHorizontal="true"
- android:layout_marginTop="28dp"
- android:ems="10"
- android:hint="Enter the Temperature"
- android:inputType="numberDecimal" />
-
-</RelativeLayout>
+++ /dev/null
-<?xml version="1.0" encoding="utf-8"?>
-<resources>
- <style name="AppTheme" parent="android:Theme.Material.Light">
- </style>
-</resources>
+++ /dev/null
-<resources>
- <string name="app_name">RESampleClientApp</string>
-
- <string name="resource_client">Resource Client</string>
- <string name="container_resource">Discover Container Resource</string>
-
- <string name="discover_resource">Discover Resource</string>
- <string name="cancel_discovery">Cancel Discovery</string>
-
-</resources>
+++ /dev/null
-<resources>
-
- <!-- Base application theme. -->
- <style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
- <!-- Customize your theme here. -->
- </style>
-
-</resources>
+++ /dev/null
-// Top-level build file where you can add configuration options common to all sub-projects/modules.
-
-buildscript {
- repositories {
- jcenter()
- }
- dependencies {
- classpath 'com.android.tools.build:gradle:1.3.0'
-
- // NOTE: Do not place your application dependencies here; they belong
- // in the individual module build.gradle files
- }
-}
-
-allprojects {
- repositories {
- jcenter()
-
- flatDir {
- dirs 'libs'
- }
- }
-}
+++ /dev/null
-include ':app'
+++ /dev/null
-.gradle
-/local.properties
-/.idea
-.DS_Store
-/build
-/captures
-/gradle
+++ /dev/null
-To build the app
-
-1. build Iotivity with TARGET_OS=android
-
-2. Copy aar files into app/libs folder
- - {Iotivity_root}/android/android_api/base/build/outputs/aar/iotivity-{TARGET_ARCH}-base-{MODE}.aar
- - {Iotivity_root}/service/resource-encapsulation/android/service/build/outputs/aar/iotivity-{TARGET_ARCH}-service-{MODE}.aar
-
-3. Configure dependencies for libs in app/build.gradle
- - default TARGET_ARCH is armeabi
- - default MODE is release
-
- for example, if you build Iotivity as follows,
-
- $scons TARGET_OS=android TARGET_ARCH=x86 RELEASE=0
-
- then, dependencies should be modified like below
-
- dependencies {
- compile(name:'iotivity-x86-service-debug', ext:'aar')
- compile(name:'iotivity-x86-base-debug', ext:'aar')
- }
-
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<module external.linked.project.id="RESampleServerApp" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$" external.system.id="GRADLE" external.system.module.group="" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
- <component name="FacetManager">
- <facet type="java-gradle" name="Java-Gradle">
- <configuration>
- <option name="BUILD_FOLDER_PATH" value="$MODULE_DIR$/build" />
- <option name="BUILDABLE" value="false" />
- </configuration>
- </facet>
- </component>
- <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_7" inherit-compiler-output="true">
- <exclude-output />
- <content url="file://$MODULE_DIR$">
- <excludeFolder url="file://$MODULE_DIR$/.gradle" />
- </content>
- <orderEntry type="inheritedJdk" />
- <orderEntry type="sourceFolder" forTests="false" />
- </component>
-</module>
\ No newline at end of file
+++ /dev/null
-/build
-/libs/*
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<module external.linked.project.id=":app" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$/.." external.system.id="GRADLE" external.system.module.group="RESampleServerApp" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
- <component name="FacetManager">
- <facet type="android-gradle" name="Android-Gradle">
- <configuration>
- <option name="GRADLE_PROJECT_PATH" value=":app" />
- </configuration>
- </facet>
- <facet type="android" name="Android">
- <configuration>
- <option name="SELECTED_BUILD_VARIANT" value="debug" />
- <option name="SELECTED_TEST_ARTIFACT" value="_android_test_" />
- <option name="ASSEMBLE_TASK_NAME" value="assembleDebug" />
- <option name="COMPILE_JAVA_TASK_NAME" value="compileDebugSources" />
- <option name="ASSEMBLE_TEST_TASK_NAME" value="assembleDebugAndroidTest" />
- <option name="COMPILE_JAVA_TEST_TASK_NAME" value="compileDebugAndroidTestSources" />
- <afterSyncTasks>
- <task>generateDebugAndroidTestSources</task>
- <task>generateDebugSources</task>
- </afterSyncTasks>
- <option name="ALLOW_USER_CONFIGURATION" value="false" />
- <option name="MANIFEST_FILE_RELATIVE_PATH" value="/src/main/AndroidManifest.xml" />
- <option name="RES_FOLDER_RELATIVE_PATH" value="/src/main/res" />
- <option name="RES_FOLDERS_RELATIVE_PATH" value="file://$MODULE_DIR$/src/main/res" />
- <option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" />
- </configuration>
- </facet>
- </component>
- <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_7" inherit-compiler-output="false">
- <output url="file://$MODULE_DIR$/build/intermediates/classes/debug" />
- <output-test url="file://$MODULE_DIR$/build/intermediates/classes/androidTest/debug" />
- <exclude-output />
- <content url="file://$MODULE_DIR$">
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/debug" isTestSource="false" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/debug" isTestSource="false" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/debug" isTestSource="false" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/debug" isTestSource="false" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/debug" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/resValues/debug" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/androidTest/debug" isTestSource="true" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/androidTest/debug" isTestSource="true" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/androidTest/debug" isTestSource="true" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/androidTest/debug" isTestSource="true" generated="true" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/androidTest/debug" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/resValues/androidTest/debug" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/res" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/resources" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/assets" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/aidl" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/java" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/jni" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/rs" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/res" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/assets" type="java-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/aidl" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/jni" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/rs" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/res" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/resources" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/assets" type="java-test-resource" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/aidl" isTestSource="true" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/java" isTestSource="true" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/jni" isTestSource="true" />
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/rs" isTestSource="true" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/assets" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/bundles" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/classes" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/coverage-instrumented-classes" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dependency-cache" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex-cache" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/exploded-aar/iotivity-armeabi-base-release/jars" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/exploded-aar/iotivity-armeabi-service-release/jars" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/jacoco" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/javaResources" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/libs" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/lint" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/manifests" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/ndk" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/pre-dexed" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/proguard" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/res" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/rs" />
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/symbols" />
- <excludeFolder url="file://$MODULE_DIR$/build/outputs" />
- <excludeFolder url="file://$MODULE_DIR$/build/tmp" />
- </content>
- <orderEntry type="jdk" jdkName="Android API 21 Platform" jdkType="Android SDK" />
- <orderEntry type="sourceFolder" forTests="false" />
- <orderEntry type="library" exported="" name="iotivity-armeabi-base-release-" level="project" />
- <orderEntry type="library" exported="" name="iotivity-armeabi-service-release-" level="project" />
- </component>
-</module>
\ No newline at end of file
+++ /dev/null
-apply plugin: 'com.android.application'
-
-android {
- compileSdkVersion 21
- buildToolsVersion "20.0.0"
-
- defaultConfig {
- applicationId "org.iotivity.service.sample.server"
- minSdkVersion 21
- targetSdkVersion 21
- versionCode 1
- versionName "1.0"
- }
- buildTypes {
- release {
- minifyEnabled false
- proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
- }
- }
-}
-
-dependencies {
- compile fileTree(dir: 'libs', include: ['*.jar'])
-
- compile(name:'iotivity-armeabi-service-release', ext:'aar')
- compile(name:'iotivity-base-armeabi-release', ext:'aar')
-}
+++ /dev/null
-# Add project specific ProGuard rules here.
-# By default, the flags in this file are appended to flags specified
-# in C:\Android/tools/proguard/proguard-android.txt
-# You can edit the include path and order by changing the proguardFiles
-# directive in build.gradle.
-#
-# For more details, see
-# http://developer.android.com/guide/developing/tools/proguard.html
-
-# Add any project specific keep options here:
-
-# If your project uses WebView with JS, uncomment the following
-# and specify the fully qualified class name to the JavaScript interface
-# class:
-#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
-# public *;
-#}
+++ /dev/null
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="org.iotivity.service.sample.server">
-
- <uses-permission android:name="android.permission.INTERNET" />
- <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
-
- <application android:allowBackup="true" android:label="@string/app_name"
- android:icon="@mipmap/ic_launcher" android:theme="@style/AppTheme">
-
- <activity
- android:name=".MainActivity"
- android:label="@string/app_name" >
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
-
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
-
- <activity android:name=".SimpleServerActivity" />
- <activity android:name=".CustomServerActivity" />
- </application>
-
-</manifest>
+++ /dev/null
-/******************************************************************
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- * <p>
- * <p>
- * <p>
- * 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
- * <p>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p>
- * 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.iotivity.service.sample.server;
-
-import java.lang.ref.WeakReference;
-
-import org.iotivity.service.RcsException;
-import org.iotivity.service.RcsResourceAttributes;
-import org.iotivity.service.RcsValue;
-import org.iotivity.service.server.RcsGetResponse;
-import org.iotivity.service.server.RcsRequest;
-import org.iotivity.service.server.RcsResourceObject;
-import org.iotivity.service.server.RcsResourceObject.GetRequestHandler;
-import org.iotivity.service.server.RcsResourceObject.OnAttributeUpdatedListener;
-import org.iotivity.service.server.RcsResourceObject.SetRequestHandler;
-import org.iotivity.service.server.RcsSetResponse;
-
-import android.app.Activity;
-import android.app.AlertDialog;
-import android.content.DialogInterface;
-import android.os.Bundle;
-import android.os.Handler;
-import android.os.Message;
-import android.util.Log;
-import android.view.View;
-import android.widget.AdapterView;
-import android.widget.AdapterView.OnItemClickListener;
-import android.widget.ArrayAdapter;
-import android.widget.Button;
-import android.widget.EditText;
-import android.widget.ListView;
-import android.widget.TextView;
-import android.widget.Toast;
-
-public class CustomServerActivity extends Activity
- implements OnItemClickListener {
- private static final String LOG_TAG = CustomServerActivity.class
- .getSimpleName();
-
- private static final int MSG_ID_PRINT_LOG = 0;
-
- private Handler mHandler;
-
- private ListView mListView;
- private TextView mLogView;
- private ArrayAdapter<Item> mItemAdapter;
-
- private RcsResourceObject mResourceObject;
-
- private GetRequestHandler mGetRequestHandler = new GetRequestHandler() {
- @Override
- public RcsGetResponse onGetRequested(RcsRequest request,
- RcsResourceAttributes attrs) {
- mHandler.obtainMessage(MSG_ID_PRINT_LOG,
- "Got a Get request from client, send default response \n"
- + "URI : " + request.getResourceUri() + "\n")
- .sendToTarget();
-
- return RcsGetResponse.defaultAction();
- }
- };
-
- private Item mGetRequestHandlerItem = new ToggleItem(
- R.string.register_get_request_handler,
- R.string.unregister_get_request_handler) {
-
- @Override
- public void execute() throws RcsException {
- if (isChecked()) {
- mResourceObject.setGetRequestHandler(null);
- } else {
- mResourceObject.setGetRequestHandler(mGetRequestHandler);
- }
- toggle();
- }
- };
-
- private SetRequestHandler mSetRequestHandler = new SetRequestHandler() {
- @Override
- public RcsSetResponse onSetRequested(RcsRequest request,
- RcsResourceAttributes attrs) {
- mHandler.obtainMessage(MSG_ID_PRINT_LOG,
- "Got a Set request from client, send default response\n"
- + "URI : " + request.getResourceUri() + "\n")
- .sendToTarget();
-
- return RcsSetResponse.defaultAction();
- }
- };
-
- private Item mSetRequestHandlerItem = new ToggleItem(
- R.string.register_set_request_handler,
- R.string.unregister_set_request_handler) {
-
- @Override
- public void execute() throws RcsException {
- if (isChecked()) {
- mResourceObject.setSetRequestHandler(null);
- } else {
- mResourceObject.setSetRequestHandler(mSetRequestHandler);
- }
- toggle();
- }
- };
-
- private OnAttributeUpdatedListener mOnAttributeUpdatedListener = new OnAttributeUpdatedListener() {
- @Override
- public void onAttributeUpdated(RcsValue oldValue, RcsValue newValue) {
- mHandler.obtainMessage(MSG_ID_PRINT_LOG,
- "attributes updated\n" + "oldValue : " + oldValue
- + ", newValue : " + newValue + "\n")
- .sendToTarget();
- }
- };
-
- private Item mAttributeUpdatedListenerItem = new ToggleItem(
- R.string.register_attribute_updated_listener,
- R.string.unregister_attribute_updated_listener) {
-
- @Override
- public void execute() throws RcsException {
- if (isChecked()) {
- mResourceObject.removeAttributeUpdatedListener(
- ResourceProperties.ATTR_KEY_TEMPERATURE);
- } else {
- mResourceObject.addAttributeUpdatedListener(
- ResourceProperties.ATTR_KEY_TEMPERATURE,
- mOnAttributeUpdatedListener);
- }
- toggle();
- }
- };
- private Item mSetTempItem = new Item() {
-
- @Override
- public String toString() {
- return getString(R.string.set_temp);
- }
-
- @Override
- public void execute() throws RcsException {
- showInputValueDialog();
- }
- };
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_custom_server);
-
- mHandler = new LocalHandler(this);
-
- mLogView = (TextView) findViewById(R.id.text_log);
- mListView = (ListView) findViewById(R.id.list_menu);
-
- initMenuList();
- }
-
- @Override
- protected void onDestroy() {
- super.onDestroy();
-
- if (mResourceObject != null)
- mResourceObject.destroy();
- }
-
- private void initMenuList() {
- // the items that will be displayed on the UI.
- Item[] items = new Item[] { mSetTempItem, mGetRequestHandlerItem,
- mSetRequestHandlerItem, mAttributeUpdatedListenerItem };
-
- mItemAdapter = new ArrayAdapter<>(this,
- android.R.layout.simple_list_item_1, items);
- mListView.setAdapter(mItemAdapter);
-
- mListView.setOnItemClickListener(this);
- }
-
- @Override
- public void onItemClick(AdapterView<?> parent, View view, int position,
- long id) {
- try {
- mItemAdapter.getItem(position).execute();
- mItemAdapter.notifyDataSetChanged();
- } catch (RcsException e) {
- showError(e.getMessage());
- }
- }
-
- public void onStartServerClick(View v) {
- Button btn = (Button) v;
- if (mResourceObject == null) {
- RcsResourceAttributes attrs = new RcsResourceAttributes();
- attrs.put(ResourceProperties.ATTR_KEY_TEMPERATURE, 10);
-
- mResourceObject = new RcsResourceObject.Builder(
- ResourceProperties.URI, ResourceProperties.TYPE,
- ResourceProperties.INTERFACE).setAttributes(attrs).build();
-
- btn.setText(R.string.stop_server);
- mListView.setVisibility(View.VISIBLE);
- mLogView.setText("Resource created successfully");
- } else {
- mResourceObject.destroy();
- mResourceObject = null;
-
- btn.setText(R.string.start_server);
- mListView.setVisibility(View.INVISIBLE);
- mLogView.setText("Resource stopped successfully");
- }
- }
-
- private void showInputValueDialog() {
- final AlertDialog dialog = new AlertDialog.Builder(this)
- .setTitle("Enter the Temperature Value")
- .setView(R.layout.dialog_content_edit_text)
- .setNegativeButton("Cancel", null).create();
-
- dialog.setButton(DialogInterface.BUTTON_POSITIVE, "OK",
- new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialogInterface,
- int which) {
-
- EditText editText = (EditText) dialog
- .findViewById(R.id.edit_text);
-
- try {
- RcsValue value = new RcsValue(Integer
- .parseInt(editText.getText().toString()));
-
- mResourceObject.setAttribute(
- ResourceProperties.ATTR_KEY_TEMPERATURE,
- value);
- printLog(
- "Attribute set successfully\nTemperature : "
- + value);
- } catch (NumberFormatException e) {
- showError("Please enter the Integer Value");
- } catch (RcsException e) {
- printLog(e);
- }
- }
- });
- dialog.show();
- }
-
- private void showError(String message) {
- Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
- Log.i(LOG_TAG, message);
- }
-
- private void printLog(String msg) {
- mLogView.setText(msg);
- Log.i(LOG_TAG, msg);
- }
-
- private void printLog(Exception e) {
- mLogView.setText(e.getMessage());
- Log.i(LOG_TAG, e.getMessage(), e);
- }
-
- private interface Item {
- void execute() throws RcsException;
- }
-
- private static class LocalHandler extends Handler {
- private WeakReference<CustomServerActivity> mActivityRef;
-
- private LocalHandler(CustomServerActivity activity) {
- mActivityRef = new WeakReference<>(activity);
- }
-
- @Override
- public void handleMessage(Message msg) {
- super.handleMessage(msg);
-
- CustomServerActivity activity = mActivityRef.get();
- if (activity == null)
- return;
-
- switch (msg.what) {
- case MSG_ID_PRINT_LOG:
- activity.printLog(msg.obj.toString());
- break;
- }
- }
- }
-
- private abstract class ToggleItem implements Item {
- private int mUncheckedStrId;
- private int mCheckedStrId;
-
- private boolean mIsChecked;
-
- public ToggleItem(int uncheckedStrId, int checkedStrId) {
- mUncheckedStrId = uncheckedStrId;
- mCheckedStrId = checkedStrId;
- }
-
- @Override
- public String toString() {
- return getString(mIsChecked ? mCheckedStrId : mUncheckedStrId);
- }
-
- protected final boolean isChecked() {
- return mIsChecked;
- }
-
- public final void toggle() {
- mIsChecked = !mIsChecked;
- }
- }
-}
+++ /dev/null
-/******************************************************************
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- * <p>
- * <p>
- * <p>
- * 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
- * <p>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p>
- * 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.iotivity.service.sample.server;
-
-import org.iotivity.base.ModeType;
-import org.iotivity.base.OcPlatform;
-import org.iotivity.base.PlatformConfig;
-import org.iotivity.base.QualityOfService;
-import org.iotivity.base.ServiceType;
-
-import android.app.Activity;
-import android.app.AlertDialog;
-import android.content.DialogInterface;
-import android.content.Intent;
-import android.net.ConnectivityManager;
-import android.os.Bundle;
-import android.util.Log;
-import android.view.View;
-
-/**
- * Starting Activity of the application responsible for configuring the
- * OcPlatform and redirecting to ServerBuilder or ResourceContainer activity as
- * per user's selection
- */
-public class MainActivity extends Activity {
-
- private static final String LOG_TAG = MainActivity.class.getSimpleName();
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
-
- if (!isWifiConnected()) {
- showWifiUnavailableDialog();
- return;
- }
-
- configurePlatform();
- }
-
- public void onSimpleServerBtnClick(View v) {
- startActivity(new Intent(this, SimpleServerActivity.class));
- }
-
- public void onCustomServerBtnClick(View v) {
- startActivity(new Intent(this, CustomServerActivity.class));
- }
-
- private void showWifiUnavailableDialog() {
- new AlertDialog.Builder(this).setTitle("Error")
- .setMessage(
- "WiFi is not enabled/connected! Please connect the WiFi and start application again...")
- .setCancelable(false)
- .setPositiveButton("OK", new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- finish();
- }
- }).create().show();
- }
-
- private boolean isWifiConnected() {
- ConnectivityManager connManager = (ConnectivityManager) getSystemService(
- CONNECTIVITY_SERVICE);
- return connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
- .isConnected();
- }
-
- private void configurePlatform() {
- OcPlatform.Configure(new PlatformConfig(getApplicationContext(),
- ServiceType.IN_PROC, ModeType.CLIENT_SERVER, "0.0.0.0", 0,
- QualityOfService.LOW));
- Log.i(LOG_TAG, "Configuration done successfully");
- }
-}
\ No newline at end of file
+++ /dev/null
-/******************************************************************
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- * <p>
- * <p>
- * <p>
- * 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
- * <p>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p>
- * 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.iotivity.service.sample.server;
-
-public class ResourceProperties {
- public static final String URI = "/a/TempSensor";
- public static final String TYPE = "oic.r.temperature.sensor";
- public static final String INTERFACE = "oic.if.";
-
- public static final String ATTR_KEY_TEMPERATURE = "Temperature";
-}
+++ /dev/null
-/******************************************************************
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- * <p/>
- * <p/>
- * <p/>
- * 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
- * <p/>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p/>
- * 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.iotivity.service.sample.server;
-
-import org.iotivity.service.RcsException;
-import org.iotivity.service.RcsResourceAttributes;
-import org.iotivity.service.RcsValue;
-import org.iotivity.service.server.RcsResourceObject;
-
-import android.app.Activity;
-import android.app.AlertDialog;
-import android.content.DialogInterface;
-import android.os.Bundle;
-import android.util.Log;
-import android.view.View;
-import android.widget.Button;
-import android.widget.EditText;
-import android.widget.TextView;
-import android.widget.Toast;
-
-/**
- * Activity for handling user's selection on UI for changing temperature. & for
- * updating UI.
- */
-public class SimpleServerActivity extends Activity {
-
- private static final String LOG_TAG = SimpleServerActivity.class
- .getSimpleName();
-
- private TextView mLogView;
- private RcsResourceObject mResourceObject;
- private View mSetTempBtn;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_simple_server);
-
- mLogView = (TextView) findViewById(R.id.text_log);
- mSetTempBtn = findViewById(R.id.btn_set_temp);
- }
-
- @Override
- protected void onDestroy() {
- super.onDestroy();
-
- if (mResourceObject != null)
- mResourceObject.destroy();
- }
-
- public void onStartServerClick(View v) {
- Button btn = (Button) v;
- if (mResourceObject == null) {
- RcsResourceAttributes attrs = new RcsResourceAttributes();
- attrs.put(ResourceProperties.ATTR_KEY_TEMPERATURE, 10);
-
- mResourceObject = new RcsResourceObject.Builder(
- ResourceProperties.URI, ResourceProperties.TYPE,
- ResourceProperties.INTERFACE).setAttributes(attrs).build();
-
- btn.setText(R.string.stop_server);
- mSetTempBtn.setEnabled(true);
- } else {
- mResourceObject.destroy();
- mResourceObject = null;
-
- btn.setText(R.string.start_server);
- mSetTempBtn.setEnabled(false);
- }
- }
-
- public void onSetTempClick(View v) {
- showInputValueDialog();
- }
-
- private void showInputValueDialog() {
- final AlertDialog dialog = new AlertDialog.Builder(this)
- .setTitle("Enter the Temperature Value")
- .setView(R.layout.dialog_content_edit_text)
- .setNegativeButton("Cancel", null).create();
-
- dialog.setButton(DialogInterface.BUTTON_POSITIVE, "OK",
- new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialogInterface,
- int which) {
-
- EditText editText = (EditText) dialog
- .findViewById(R.id.edit_text);
-
- try {
- RcsValue value = new RcsValue(Integer
- .parseInt(editText.getText().toString()));
-
- mResourceObject.setAttribute(
- ResourceProperties.ATTR_KEY_TEMPERATURE,
- value);
- printLog(
- "Attribute set successfully\nTemperature : "
- + value);
- } catch (NumberFormatException e) {
- showError("Please enter the Integer Value");
- } catch (RcsException e) {
- printLog(e);
- }
- }
- });
- dialog.show();
- }
-
- private void showError(String message) {
- Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
- Log.i(LOG_TAG, message);
- }
-
- private void printLog(String msg) {
- Log.e(LOG_TAG, msg);
- mLogView.setText(msg);
- }
-
- private void printLog(Exception e) {
- Log.e(LOG_TAG, e.getMessage(), e);
- mLogView.setText(e.getMessage());
- }
-}
+++ /dev/null
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical">
-
- <Button
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:onClick="onStartServerClick"
- android:text="@string/start_server" />
-
- <ListView
- android:id="@+id/list_menu"
- android:layout_width="match_parent"
- android:layout_height="0dp"
- android:layout_weight="1"
- android:visibility="invisible" />
-
- <TextView
- android:id="@+id/text_log"
- android:layout_width="fill_parent"
- android:layout_height="250dp"
- android:layout_marginTop="15dp"
- android:ems="10" />
-
-</LinearLayout>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="utf-8"?>
-
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical">
-
- <Button
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="@string/simple_sever"
- android:onClick="onSimpleServerBtnClick" />
-
- <Button
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="@string/custom_sever"
- android:onClick="onCustomServerBtnClick" />
-
-</LinearLayout>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical">
-
- <Button
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:onClick="onStartServerClick"
- android:text="@string/start_server" />
-
- <Button
- android:id="@+id/btn_set_temp"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:enabled="false"
- android:onClick="onSetTempClick"
- android:text="@string/set_temp" />
-
- <TextView
- android:id="@+id/text_log"
- android:layout_width="fill_parent"
- android:layout_height="250dp"
- android:layout_marginTop="15dp"
- android:ems="10" />
-
-</LinearLayout>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="utf-8"?>
-<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical">
-
- <EditText
- android:id="@+id/edit_text"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentTop="true"
- android:layout_centerHorizontal="true"
- android:layout_marginTop="28dp"
- android:ems="10"
- android:hint="Enter the Temperature"
- android:inputType="numberDecimal" />
-
-</RelativeLayout>
+++ /dev/null
-<?xml version="1.0" encoding="utf-8"?>
-<resources>
- <style name="AppTheme" parent="android:Theme.Material.Light">
- </style>
-</resources>
+++ /dev/null
-<resources>
- <string name="app_name">RESampleServerApp</string>
-
- <string name="start_server">Start</string>
- <string name="stop_server">Stop Server</string>
-
- <string name="set_temp">Set Temperature</string>
-
- <string name="simple_sever">Simple Server</string>
- <string name="custom_sever">Custom Server</string>
-
- <string name="register_get_request_handler">Register GetRequestHandler</string>
- <string name="unregister_get_request_handler">Unregister GetRequestHandler</string>
-
- <string name="register_set_request_handler">Register SetRequestHandler</string>
- <string name="unregister_set_request_handler">Unregister SetRequestHandler</string>
-
- <string name="register_attribute_updated_listener">Register AttributeUpdatedListener</string>
- <string name="unregister_attribute_updated_listener">Unregister AttributeUpdatedListener</string>
-</resources>
+++ /dev/null
-<resources>
-
- <!-- Base application theme. -->
- <style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
- <!-- Customize your theme here. -->
- </style>
-
-</resources>
+++ /dev/null
-// Top-level build file where you can add configuration options common to all sub-projects/modules.
-
-buildscript {
- repositories {
- jcenter()
- }
- dependencies {
- classpath 'com.android.tools.build:gradle:1.3.0'
-
- // NOTE: Do not place your application dependencies here; they belong
- // in the individual module build.gradle files
- }
-}
-
-allprojects {
- repositories {
- jcenter()
-
- flatDir {
- dirs 'libs'
- }
- }
-}
+++ /dev/null
-include ':app'
+++ /dev/null
-diff -Naur /home/joseph/Desktop/old_arduino/arduino-1.0.5/libraries/Ethernet/Ethernet.cpp /home/joseph/Desktop/arduino-1.0.5/./libraries/Ethernet/Ethernet.cpp
---- /home/joseph/Desktop/old_arduino/arduino-1.0.5/libraries/Ethernet/Ethernet.cpp 2013-05-17 14:22:15.000000000 -0400
-+++ /home/joseph/Desktop/arduino-1.0.5/./libraries/Ethernet/Ethernet.cpp 2014-10-20 17:14:17.422407860 -0400
-@@ -7,10 +7,10 @@
- 0, 0, 0, 0 };
- uint16_t EthernetClass::_server_port[MAX_SOCK_NUM] = {
- 0, 0, 0, 0 };
-+static DhcpClass s_dhcp;
-
- int EthernetClass::begin(uint8_t *mac_address)
- {
-- static DhcpClass s_dhcp;
- _dhcp = &s_dhcp;
-
-
-diff -Naur /home/joseph/Desktop/old_arduino/arduino-1.0.5/libraries/Ethernet/utility/socket.cpp /home/joseph/Desktop/arduino-1.0.5/./libraries/Ethernet/utility/socket.cpp
---- /home/joseph/Desktop/old_arduino/arduino-1.0.5/libraries/Ethernet/utility/socket.cpp 2013-05-17 14:22:15.000000000 -0400
-+++ /home/joseph/Desktop/arduino-1.0.5/./libraries/Ethernet/utility/socket.cpp 2014-10-20 17:38:25.170471548 -0400
-@@ -248,6 +248,7 @@
- {
- uint8_t head[8];
- uint16_t data_len=0;
-+ uint16_t data_copied=0;
- uint16_t ptr=0;
-
- if ( len > 0 )
-@@ -285,10 +286,6 @@
- data_len = head[4];
- data_len = (data_len << 8) + head[5];
-
-- W5100.read_data(s, (uint8_t *)ptr, buf, data_len); // data copy.
-- ptr += data_len;
--
-- W5100.writeSnRX_RD(s, ptr);
- break;
-
- case SnMR::MACRAW:
-@@ -297,17 +294,22 @@
- data_len = head[0];
- data_len = (data_len<<8) + head[1] - 2;
-
-- W5100.read_data(s,(uint8_t*) ptr,buf,data_len);
-- ptr += data_len;
-- W5100.writeSnRX_RD(s, ptr);
- break;
-
- default :
- break;
- }
-+
-+ if (data_len > 0)
-+ {
-+ data_copied = (data_len <= len) ? data_len : len;// only copy the len bytes, rest of is discarded.
-+ W5100.read_data(s, (uint8_t *)ptr, buf, data_copied); // data copy.
-+ ptr += data_len;
-+ W5100.writeSnRX_RD(s, ptr);
-+ }
- W5100.execCmdSn(s, Sock_RECV);
- }
-- return data_len;
-+ return data_copied;
- }
-
-
-diff -Naur /home/joseph/Desktop/old_arduino/arduino-1.0.5/libraries/WiFi/utility/wifi_spi.h /home/joseph/Desktop/arduino-1.0.5/./libraries/WiFi/utility/wifi_spi.h
---- /home/joseph/Desktop/old_arduino/arduino-1.0.5/libraries/WiFi/utility/wifi_spi.h 2013-05-17 14:22:16.000000000 -0400
-+++ /home/joseph/Desktop/arduino-1.0.5/./libraries/WiFi/utility/wifi_spi.h 2014-10-20 17:39:26.018474225 -0400
-@@ -56,13 +56,13 @@
- GET_FW_VERSION_CMD = 0x37,
- GET_TEST_CMD = 0x38,
- SEND_DATA_UDP_CMD = 0x39,
-- GET_REMOTE_DATA_CMD = 0x3A,\r
-+ GET_REMOTE_DATA_CMD = 0x3A,
-
- // All command with DATA_FLAG 0x40 send a 16bit Len
-
- SEND_DATA_TCP_CMD = 0x44,
- GET_DATABUF_TCP_CMD = 0x45,
-- INSERT_DATABUF_CMD = 0x46,
-+ INSERT_DATABUF_CMD = 0x46
- };
-
-
-diff -Naur /home/joseph/Desktop/old_arduino/arduino-1.0.5/libraries/WiFi/utility/wl_types.h /home/joseph/Desktop/arduino-1.0.5/./libraries/WiFi/utility/wl_types.h
---- /home/joseph/Desktop/old_arduino/arduino-1.0.5/libraries/WiFi/utility/wl_types.h 2013-05-17 14:22:16.000000000 -0400
-+++ /home/joseph/Desktop/arduino-1.0.5/./libraries/WiFi/utility/wl_types.h 2014-10-20 17:17:23.858416062 -0400
-@@ -13,7 +13,7 @@
- \r
- typedef enum {\r
- WL_FAILURE = -1,\r
-- WL_SUCCESS = 1,\r
-+ WL_SUCCESS = 1\r
- } wl_error_code_t;\r
- \r
- /* Authentication modes */\r
+++ /dev/null
-diff -Naur /home/joseph/Desktop/old_arduino/arduino-1.5.7/libraries/Ethernet/src/Ethernet.cpp /home/joseph/Desktop/arduino-1.5.7/./libraries/Ethernet/src/Ethernet.cpp
---- /home/joseph/Desktop/old_arduino/arduino-1.5.7/libraries/Ethernet/src/Ethernet.cpp 2014-07-07 04:11:39.000000000 -0400
-+++ /home/joseph/Desktop/arduino-1.5.7/./libraries/Ethernet/src/Ethernet.cpp 2014-10-20 17:14:19.666407959 -0400
-@@ -7,10 +7,10 @@
- 0, 0, 0, 0 };
- uint16_t EthernetClass::_server_port[MAX_SOCK_NUM] = {
- 0, 0, 0, 0 };
-+static DhcpClass s_dhcp;
-
- int EthernetClass::begin(uint8_t *mac_address)
- {
-- static DhcpClass s_dhcp;
- _dhcp = &s_dhcp;
-
-
-diff -Naur /home/joseph/Desktop/old_arduino/arduino-1.5.7/libraries/Ethernet/src/utility/socket.cpp /home/joseph/Desktop/arduino-1.5.7/./libraries/Ethernet/src/utility/socket.cpp
---- /home/joseph/Desktop/old_arduino/arduino-1.5.7/libraries/Ethernet/src/utility/socket.cpp 2014-07-07 04:11:39.000000000 -0400
-+++ /home/joseph/Desktop/arduino-1.5.7/./libraries/Ethernet/src/utility/socket.cpp 2014-10-20 17:16:31.834413773 -0400
-@@ -248,6 +248,7 @@
- {
- uint8_t head[8];
- uint16_t data_len=0;
-+ uint16_t data_copied=0;
- uint16_t ptr=0;
-
- if ( len > 0 )
-@@ -285,10 +286,6 @@
- data_len = head[4];
- data_len = (data_len << 8) + head[5];
-
-- W5100.read_data(s, ptr, buf, data_len); // data copy.
-- ptr += data_len;
--
-- W5100.writeSnRX_RD(s, ptr);
- break;
-
- case SnMR::MACRAW:
-@@ -297,17 +294,22 @@
- data_len = head[0];
- data_len = (data_len<<8) + head[1] - 2;
-
-- W5100.read_data(s, ptr, buf, data_len);
-- ptr += data_len;
-- W5100.writeSnRX_RD(s, ptr);
- break;
-
- default :
- break;
- }
-+
-+ if (data_len > 0)
-+ {
-+ data_copied = (data_len <= len) ? data_len : len;// only copy the len bytes, rest of is discarded.
-+ W5100.read_data(s, ptr, buf, data_copied); // data copy.
-+ ptr += data_len;
-+ W5100.writeSnRX_RD(s, ptr);
-+ }
- W5100.execCmdSn(s, Sock_RECV);
- }
-- return data_len;
-+ return data_copied;
- }
-
- /**
-diff -Naur /home/joseph/Desktop/old_arduino/arduino-1.5.7/libraries/WiFi/src/utility/wifi_spi.h /home/joseph/Desktop/arduino-1.5.7/./libraries/WiFi/src/utility/wifi_spi.h
---- /home/joseph/Desktop/old_arduino/arduino-1.5.7/libraries/WiFi/src/utility/wifi_spi.h 2014-07-07 04:11:40.000000000 -0400
-+++ /home/joseph/Desktop/arduino-1.5.7/./libraries/WiFi/src/utility/wifi_spi.h 2014-10-20 17:17:59.490417629 -0400
-@@ -82,7 +82,7 @@
-
- SEND_DATA_TCP_CMD = 0x44,
- GET_DATABUF_TCP_CMD = 0x45,
-- INSERT_DATABUF_CMD = 0x46,
-+ INSERT_DATABUF_CMD = 0x46
- };
-
-
-diff -Naur /home/joseph/Desktop/old_arduino/arduino-1.5.7/libraries/WiFi/src/utility/wl_types.h /home/joseph/Desktop/arduino-1.5.7/./libraries/WiFi/src/utility/wl_types.h
---- /home/joseph/Desktop/old_arduino/arduino-1.5.7/libraries/WiFi/src/utility/wl_types.h 2014-07-07 04:11:40.000000000 -0400
-+++ /home/joseph/Desktop/arduino-1.5.7/./libraries/WiFi/src/utility/wl_types.h 2014-10-20 17:17:25.754416145 -0400
-@@ -31,7 +31,7 @@
- \r
- typedef enum {\r
- WL_FAILURE = -1,\r
-- WL_SUCCESS = 1,\r
-+ WL_SUCCESS = 1\r
- } wl_error_code_t;\r
- \r
- /* Authentication modes */\r
+++ /dev/null
-#!/bin/bash
-
-# change this to what version of Xcode you have installed
-
-scons TARGET_OS=ios TARGET_ARCH=armv7 RELEASE=false
-scons TARGET_OS=ios TARGET_ARCH=armv7s RELEASE=false
-scons TARGET_OS=ios TARGET_ARCH=arm64 RELEASE=false
-scons TARGET_OS=ios TARGET_ARCH=i386 RELEASE=false
-scons TARGET_OS=ios TARGET_ARCH=x86_64 RELEASE=false
+++ /dev/null
-#!/bin/sh
-#===============================================================================
-# Author: Pete Goodliffe
-# Copyright: (c) Copyright 2009 Pete Goodliffe
-# Licence: Please feel free to use this, with attribution
-#===============================================================================
-
-#VERSION_IOS="${MAJOR_VERSION}.${MINOR_VERSION}.${RELEASE_NUMBER}.${BUILD_NUMBER}"
-VERSION_IOS="0.9.0.1"
-
-
-OUTDIR=$PWD/out/ios
-BUILD=debug
-LIBCOAP=libcoap
-SDKLIB=liboctbstack
-LIPO="xcrun -sdk iphoneos lipo"
-
-
-VERSION_TYPE=Alpha
-FRAMEWORK_NAME=iotivity-csdk
-FRAMEWORK_VERSION=A
-FRAMEWORK_CURRENT_VERSION=${VERSION_IOS}
-FRAMEWORK_COMPATIBILITY_VERSION=${VERSION_IOS}
-FRAMEWORKDIR=out/ios
-
-FRAMEWORK_BUNDLE=$FRAMEWORKDIR/$FRAMEWORK_NAME.framework
-rm -rf $FRAMEWORK_BUNDLE
-
-echo "Framework: Setting up directories..."
-mkdir -p $FRAMEWORK_BUNDLE
-mkdir -p $FRAMEWORK_BUNDLE/Versions
-mkdir -p $FRAMEWORK_BUNDLE/Versions/$FRAMEWORK_VERSION
-mkdir -p $FRAMEWORK_BUNDLE/Versions/$FRAMEWORK_VERSION/Resources
-mkdir -p $FRAMEWORK_BUNDLE/Versions/$FRAMEWORK_VERSION/Headers
-mkdir -p $FRAMEWORK_BUNDLE/Versions/$FRAMEWORK_VERSION/Documentation
-
-echo "Framework: Creating symlinks..."
-ln -s $FRAMEWORK_VERSION $FRAMEWORK_BUNDLE/Versions/Current
-ln -s Versions/Current/Headers $FRAMEWORK_BUNDLE/Headers
-ln -s Versions/Current/Resources $FRAMEWORK_BUNDLE/Resources
-ln -s Versions/Current/Documentation $FRAMEWORK_BUNDLE/Documentation
-ln -s Versions/Current/$FRAMEWORK_NAME $FRAMEWORK_BUNDLE/$FRAMEWORK_NAME
-FRAMEWORK_INSTALL_NAME=$FRAMEWORK_BUNDLE/Versions/$FRAMEWORK_VERSION/$FRAMEWORK_NAME
-
-lipolite()
-{
- PREV="$PWD"
- cd "$1"
- ar -x "$2"
- cd "$PREV"
-}
-
-
-echo "Extracting libraries..."
-mkdir $OUTDIR/objs
-
-ARCHS="armv7 armv7s arm64 i386 x86_64"
-FATFILE=""
-
-for ARCH in $ARCHS
-do
- echo "extracting $ARCH"
- mkdir $OUTDIR/objs/$ARCH
- lipolite $OUTDIR/objs/$ARCH "$OUTDIR/$ARCH/$BUILD/$LIBCOAP.a"
- lipolite $OUTDIR/objs/$ARCH "$OUTDIR/$ARCH/$BUILD/$SDKLIB.a"
- ar -r $OUTDIR/objs/$ARCH.a $OUTDIR/objs/$ARCH/*.o
-done
-
-
-echo "Lipoing library into $FRAMEWORK_INSTALL_NAME..."
-$LIPO \
- -create \
- -arch armv7 "$OUTDIR/objs/armv7.a" \
- -arch armv7s "$OUTDIR/objs/armv7s.a" \
- -arch arm64 "$OUTDIR/objs/arm64.a" \
- -arch i386 "$OUTDIR/objs/i386.a" \
- -arch x86_64 "$OUTDIR/objs/x86_64.a" \
- -output "$FRAMEWORK_INSTALL_NAME" \
- || abort "Lipo $1 failed"
-
-echo rm -rf objs
-find $OUTDIR/objs -name "*.o" | xargs rm
-
-echo "Framework: Copying includes..."
-cp -r resource/csdk/stack/include/*.h $FRAMEWORK_BUNDLE/Headers
-cp -r resource/csdk/ocsocket/include/*.h $FRAMEWORK_BUNDLE/Headers
-cp -r resource/c_common/ocrandom/include/*.h $FRAMEWORK_BUNDLE/Headers
-cp -r resource/c_common/oic_malloc/include/*.h $FRAMEWORK_BUNDLE/Headers
-
-echo "Framework: Creating plist..."
-cat > $FRAMEWORK_BUNDLE/Resources/Info.plist <<EOF
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
-<plist version="1.0">
-<dict>
- <key>CFBundleDevelopmentRegion</key>
- <string>English</string>
- <key>CFBundleExecutable</key>
- <string>${FRAMEWORK_NAME}</string>
- <key>CFBundleIdentifier</key>
- <string>org.iotivity</string>
- <key>CFBundleInfoDictionaryVersion</key>
- <string>6.0</string>
- <key>CFBundlePackageType</key>
- <string>FMWK</string>
- <key>CFBundleSignature</key>
- <string>????</string>
- <key>CFBundleVersion</key>
- <string>${FRAMEWORK_CURRENT_VERSION}</string>
-</dict>
-</plist>
-EOF
-
-echo
-echo " ================================================================="
-echo " Done"
-echo
+++ /dev/null
-#!/bin/sh
-#===============================================================================
-# Author: Pete Goodliffe
-# Copyright: (c) Copyright 2009 Pete Goodliffe
-# Licence: Please feel free to use this, with attribution
-#===============================================================================
-
-#VERSION_IOS="${MAJOR_VERSION}.${MINOR_VERSION}.${RELEASE_NUMBER}.${BUILD_NUMBER}"
-VERSION_IOS="0.9.0.1"
-
-
-OUTDIR=$PWD/out/darwin
-BUILD=debug
-LIBCOAP=libcoap
-SDKLIB=liboctbstack
-LIPO="xcrun -sdk iphoneos lipo"
-
-
-VERSION_TYPE=Alpha
-FRAMEWORK_NAME=iotivity-csdk
-FRAMEWORK_VERSION=A
-FRAMEWORK_CURRENT_VERSION=${VERSION_IOS}
-FRAMEWORK_COMPATIBILITY_VERSION=${VERSION_IOS}
-FRAMEWORKDIR=out/darwin
-
-FRAMEWORK_BUNDLE=$FRAMEWORKDIR/$FRAMEWORK_NAME.framework
-rm -rf $FRAMEWORK_BUNDLE
-
-echo "Framework: Setting up directories..."
-mkdir -p $FRAMEWORK_BUNDLE
-mkdir -p $FRAMEWORK_BUNDLE/Versions
-mkdir -p $FRAMEWORK_BUNDLE/Versions/$FRAMEWORK_VERSION
-mkdir -p $FRAMEWORK_BUNDLE/Versions/$FRAMEWORK_VERSION/Resources
-mkdir -p $FRAMEWORK_BUNDLE/Versions/$FRAMEWORK_VERSION/Headers
-mkdir -p $FRAMEWORK_BUNDLE/Versions/$FRAMEWORK_VERSION/Documentation
-
-echo "Framework: Creating symlinks..."
-ln -s $FRAMEWORK_VERSION $FRAMEWORK_BUNDLE/Versions/Current
-ln -s Versions/Current/Headers $FRAMEWORK_BUNDLE/Headers
-ln -s Versions/Current/Resources $FRAMEWORK_BUNDLE/Resources
-ln -s Versions/Current/Documentation $FRAMEWORK_BUNDLE/Documentation
-ln -s Versions/Current/$FRAMEWORK_NAME $FRAMEWORK_BUNDLE/$FRAMEWORK_NAME
-FRAMEWORK_INSTALL_NAME=$FRAMEWORK_BUNDLE/Versions/$FRAMEWORK_VERSION/$FRAMEWORK_NAME
-
-lipolite()
-{
- PREV="$PWD"
- cd "$1"
- ar -x "$2"
- cd "$PREV"
-}
-
-
-echo "Extracting libraries..."
-mkdir $OUTDIR/objs
-
-ARCHS="x86_64"
-FATFILE=""
-
-for ARCH in $ARCHS
-do
- echo "extracting $ARCH"
- mkdir $OUTDIR/objs/$ARCH
- lipolite $OUTDIR/objs/$ARCH "$OUTDIR/$ARCH/$BUILD/$LIBCOAP.a"
- lipolite $OUTDIR/objs/$ARCH "$OUTDIR/$ARCH/$BUILD/$SDKLIB.a"
- ar -r $OUTDIR/objs/$ARCH.a $OUTDIR/objs/$ARCH/*.o
-done
-
-
-echo "Lipoing library into $FRAMEWORK_INSTALL_NAME..."
-cp $OUTDIR/objs/x86_64.a "$FRAMEWORK_INSTALL_NAME"
-
-#$LIPO \
-# -create \
-# -arch armv7 "$OUTDIR/objs/armv7.a" \
-# -arch armv7s "$OUTDIR/objs/armv7s.a" \
-# -arch arm64 "$OUTDIR/objs/arm64.a" \
-# -arch i386 "$OUTDIR/objs/i386.a" \
-# -arch x86_64 "$OUTDIR/objs/x86_64.a" \
-# -output "$FRAMEWORK_INSTALL_NAME" \
-# || abort "Lipo $1 failed"
-
-echo rm -rf objs
-find $OUTDIR/objs -name "*.o" | xargs rm
-
-echo "Framework: Copying includes..."
-cp -r resource/csdk/stack/include/*.h $FRAMEWORK_BUNDLE/Headers
-cp -r resource/c_common/ocrandom/include/*.h $FRAMEWORK_BUNDLE/Headers
-cp -r resource/c_common/oic_malloc/include/*.h $FRAMEWORK_BUNDLE/Headers
-
-echo "Framework: Creating plist..."
-cat > $FRAMEWORK_BUNDLE/Resources/Info.plist <<EOF
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
-<plist version="1.0">
-<dict>
- <key>CFBundleDevelopmentRegion</key>
- <string>English</string>
- <key>CFBundleExecutable</key>
- <string>${FRAMEWORK_NAME}</string>
- <key>CFBundleIdentifier</key>
- <string>org.iotivity</string>
- <key>CFBundleInfoDictionaryVersion</key>
- <string>6.0</string>
- <key>CFBundlePackageType</key>
- <string>FMWK</string>
- <key>CFBundleSignature</key>
- <string>????</string>
- <key>CFBundleVersion</key>
- <string>${FRAMEWORK_CURRENT_VERSION}</string>
-</dict>
-</plist>
-EOF
-
-echo
-echo " ================================================================="
-echo " Done"
-echo