├── lib ├── .gitignore ├── gradle.properties ├── src │ ├── main │ │ ├── res │ │ │ ├── values │ │ │ │ └── strings.xml │ │ │ ├── drawable-hdpi │ │ │ │ └── ic_launcher.png │ │ │ ├── drawable-mdpi │ │ │ │ └── ic_launcher.png │ │ │ ├── drawable-xhdpi │ │ │ │ └── ic_launcher.png │ │ │ └── drawable-xxhdpi │ │ │ │ └── ic_launcher.png │ │ ├── jni-src │ │ │ └── jni │ │ │ │ ├── Application.mk │ │ │ │ ├── leveldbjni.h │ │ │ │ ├── Android.mk │ │ │ │ └── leveldbjni.cc │ │ ├── jniLibs │ │ │ ├── armeabi │ │ │ │ └── libleveldbjni.so │ │ │ └── armeabi-v7a │ │ │ │ └── libleveldbjni.so │ │ ├── AndroidManifest.xml │ │ └── java │ │ │ └── im │ │ │ └── amomo │ │ │ └── leveldb │ │ │ ├── LevelDBException.java │ │ │ ├── DBFactory.java │ │ │ └── LevelDB.java │ └── androidTest │ │ └── java │ │ └── im │ │ └── amomo │ │ └── leveldb │ │ └── TestDB.java ├── proguard-rules.txt └── build.gradle ├── sample ├── .gitignore ├── src │ └── main │ │ ├── res │ │ ├── drawable-hdpi │ │ │ └── ic_launcher.png │ │ ├── drawable-mdpi │ │ │ └── ic_launcher.png │ │ ├── drawable-xhdpi │ │ │ └── ic_launcher.png │ │ ├── drawable-xxhdpi │ │ │ └── ic_launcher.png │ │ ├── values │ │ │ ├── styles.xml │ │ │ ├── dimens.xml │ │ │ └── strings.xml │ │ ├── layout │ │ │ ├── activity_main.xml │ │ │ └── fragment_main.xml │ │ ├── values-w820dp │ │ │ └── dimens.xml │ │ └── menu │ │ │ └── main.xml │ │ ├── AndroidManifest.xml │ │ └── java │ │ └── im │ │ └── amomo │ │ └── leveldb │ │ └── sample │ │ └── MainActivity.java ├── build.gradle └── proguard-rules.txt ├── settings.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── configure.sh ├── .gitignore ├── .gitmodules ├── README.md ├── gradle.properties ├── gradlew.bat ├── gradlew └── LICENSE.md /lib/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /sample/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':lib', ':sample' 2 | -------------------------------------------------------------------------------- /lib/gradle.properties: -------------------------------------------------------------------------------- 1 | POM_NAME=Leveldb-Android 2 | POM_ARTIFACT_ID=leveldb 3 | POM_PACKAGING=aar 4 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/googolmo/Leveldb-Android/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /lib/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | LevelDB-Adroid 3 | 4 | -------------------------------------------------------------------------------- /lib/src/main/jni-src/jni/Application.mk: -------------------------------------------------------------------------------- 1 | APP_PLATFORM=android-9 2 | APP_ABI := armeabi armeabi-v7a 3 | APP_STL := stlport_static 4 | -------------------------------------------------------------------------------- /configure.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | git submodule init 4 | git submodule update 5 | sh lib/src/main/jni-src/jni/snappy/autogen.sh 6 | -------------------------------------------------------------------------------- /lib/src/main/jniLibs/armeabi/libleveldbjni.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/googolmo/Leveldb-Android/HEAD/lib/src/main/jniLibs/armeabi/libleveldbjni.so -------------------------------------------------------------------------------- /lib/src/main/res/drawable-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/googolmo/Leveldb-Android/HEAD/lib/src/main/res/drawable-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /lib/src/main/res/drawable-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/googolmo/Leveldb-Android/HEAD/lib/src/main/res/drawable-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /lib/src/main/jniLibs/armeabi-v7a/libleveldbjni.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/googolmo/Leveldb-Android/HEAD/lib/src/main/jniLibs/armeabi-v7a/libleveldbjni.so -------------------------------------------------------------------------------- /lib/src/main/res/drawable-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/googolmo/Leveldb-Android/HEAD/lib/src/main/res/drawable-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /lib/src/main/res/drawable-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/googolmo/Leveldb-Android/HEAD/lib/src/main/res/drawable-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/drawable-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/googolmo/Leveldb-Android/HEAD/sample/src/main/res/drawable-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/drawable-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/googolmo/Leveldb-Android/HEAD/sample/src/main/res/drawable-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/drawable-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/googolmo/Leveldb-Android/HEAD/sample/src/main/res/drawable-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/drawable-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/googolmo/Leveldb-Android/HEAD/sample/src/main/res/drawable-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | /local.properties 3 | /.idea/workspace.xml 4 | .DS_Store 5 | *.iml 6 | .idea 7 | lib/src/main/jni-src/obj/ 8 | lib/src/main/jni-src/libs/ 9 | -------------------------------------------------------------------------------- /sample/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /sample/src/main/res/values/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 16dp 4 | 16dp 5 | 6 | 7 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "lib/src/main/jni-src/jni/leveldb"] 2 | path = lib/src/main/jni-src/jni/leveldb 3 | url = https://code.google.com/p/leveldb/ 4 | [submodule "lib/src/main/jni-src/jni/snappy"] 5 | path = lib/src/main/jni-src/jni/snappy 6 | url = https://github.com/google/snappy.git 7 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Thu Mar 27 10:47:30 CST 2014 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=http\://services.gradle.org/distributions/gradle-1.11-bin.zip 7 | -------------------------------------------------------------------------------- /sample/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | LevelDB-Adroid 5 | Hello world! 6 | Settings 7 | 8 | 9 | -------------------------------------------------------------------------------- /lib/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /sample/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 8 | -------------------------------------------------------------------------------- /sample/src/main/res/values-w820dp/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 64dp 6 | 7 | -------------------------------------------------------------------------------- /sample/src/main/res/menu/main.xml: -------------------------------------------------------------------------------- 1 | 4 | 5 | 9 | 10 | -------------------------------------------------------------------------------- /lib/src/main/java/im/amomo/leveldb/LevelDBException.java: -------------------------------------------------------------------------------- 1 | package im.amomo.leveldb; 2 | 3 | /** 4 | * Created by GoogolMo on 3/13/14. 5 | */ 6 | public class LevelDBException extends RuntimeException { 7 | 8 | public LevelDBException() { 9 | } 10 | 11 | public LevelDBException(String error) { 12 | super(error); 13 | } 14 | 15 | public LevelDBException(String error, Throwable cause) { 16 | super(error, cause); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /lib/src/main/jni-src/jni/leveldbjni.h: -------------------------------------------------------------------------------- 1 | #ifndef LEVELDBJNI_H_ 2 | #define LEVELDBJNI_H_ 3 | 4 | #include 5 | #include 6 | #include "leveldb/db.h" 7 | 8 | # define NELEM(x) ((int) (sizeof(x) / sizeof((x)[0]))) 9 | #define LOG_TAG "LevelDB" 10 | #define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__) 11 | #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__) 12 | 13 | jint throwException(JNIEnv* env, const char* msg); 14 | 15 | void releaseDB(); 16 | 17 | #endif /* LEVELDBJNI_H_ */ 18 | -------------------------------------------------------------------------------- /sample/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'android' 2 | 3 | group = project.GROUP 4 | 5 | android { 6 | compileSdkVersion 19 7 | buildToolsVersion "19.0.3" 8 | 9 | defaultConfig { 10 | minSdkVersion 14 11 | targetSdkVersion 19 12 | versionCode Integer.parseInt(project.VERSION_CODE) 13 | versionName project.VERSION_NAME 14 | } 15 | buildTypes { 16 | release { 17 | runProguard false 18 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt' 19 | } 20 | } 21 | } 22 | 23 | dependencies { 24 | compile fileTree(dir: 'libs', include: ['*.jar']) 25 | compile project(":lib") 26 | } 27 | -------------------------------------------------------------------------------- /lib/proguard-rules.txt: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /Volumes/HDD/opt/android-sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the ProGuard 5 | # include property in project.properties. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} -------------------------------------------------------------------------------- /sample/proguard-rules.txt: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /Volumes/HDD/opt/android-sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the ProGuard 5 | # include property in project.properties. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} -------------------------------------------------------------------------------- /sample/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 10 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /sample/src/main/res/layout/fragment_main.xml: -------------------------------------------------------------------------------- 1 | 10 | 11 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /lib/src/main/java/im/amomo/leveldb/DBFactory.java: -------------------------------------------------------------------------------- 1 | package im.amomo.leveldb; 2 | 3 | import android.content.Context; 4 | import android.os.Environment; 5 | import android.util.Log; 6 | 7 | import java.io.File; 8 | 9 | /** 10 | * Created by GoogolMo on 3/25/14. 11 | */ 12 | public class DBFactory { 13 | 14 | private final static String DEFAULT_DATABASE_NAME = "leveldb"; 15 | 16 | public static LevelDB open(File dbPath) throws LevelDBException { 17 | return new LevelDB(dbPath); 18 | } 19 | 20 | public static LevelDB open(Context context, String dbName) throws LevelDBException { 21 | File dbPath; 22 | try { 23 | dbPath = context.getExternalFilesDir(null); 24 | } catch (Exception e) { 25 | dbPath = context.getFilesDir(); 26 | } 27 | return open(new File(dbPath, dbName)); 28 | } 29 | 30 | public static LevelDB open(Context context) throws LevelDBException { 31 | return open(context, DEFAULT_DATABASE_NAME); 32 | } 33 | 34 | 35 | } 36 | -------------------------------------------------------------------------------- /lib/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'android-library' 2 | 3 | group = project.GROUP 4 | version = project.VERSION_NAME 5 | 6 | android { 7 | compileSdkVersion 19 8 | buildToolsVersion "19.0.3" 9 | 10 | defaultConfig { 11 | minSdkVersion 8 12 | targetSdkVersion 19 13 | versionCode Integer.parseInt(project.VERSION_CODE) 14 | versionName project.VERSION_NAME 15 | ndk { 16 | moduleName "leveldbjni" 17 | } 18 | } 19 | 20 | buildTypes { 21 | release { 22 | runProguard false 23 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt' 24 | } 25 | } 26 | } 27 | 28 | dependencies { 29 | compile fileTree(dir: 'libs', include: ['*.jar']) 30 | } 31 | 32 | // query for all (non-test) variants and inject a new step in the builds 33 | android.libraryVariants.all { variant -> 34 | def jarTask = project.tasks.create(name:"jar${variant.name.capitalize()}", type: Jar) { 35 | from variant.javaCompile.destinationDir 36 | exclude "**/R.class" 37 | exclude "**/BuildConfig.class" 38 | } 39 | jarTask.dependsOn variant.javaCompile 40 | artifacts.add('archives', jarTask); 41 | } 42 | 43 | apply from: 'https://raw.github.com/googolmo/gradle-mvn-push/master/gradle-mvn-push.gradle' 44 | 45 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Leveldb-Android 2 | =============== 3 | 4 | Port leveldb to Android 5 | 6 | ====================== 7 | 8 | [![Build Status](https://drone.io/github.com/googolmo/Leveldb-Android/status.png)](https://drone.io/github.com/googolmo/Leveldb-Android/latest) 9 | 10 | ###Build 11 | 1. Configure Project 12 | ```bash 13 | ./configure.sh 14 | ``` 15 | 16 | 2. Build jni and copy so file 17 | ```bash 18 | ./build.sh 19 | ``` 20 | 21 | 3. Build Project 22 | ```bash 23 | ./gradlew build 24 | ``` 25 | 26 | ### How to import 27 | 28 | * aar (may be can't work) 29 | 30 | ```groovy 31 | dependencies { 32 | compile 'im.amomo.leveldb:leveldb:1.0.1@aar' 33 | } 34 | ``` 35 | 36 | * remote jar and local so 37 | 38 | ```groovy 39 | dependencies { 40 | compile 'im.amomo.leveldb:leveldb:1.0.1@jar' 41 | } 42 | ``` 43 | 44 | save [armeabi/libleveldbjni.so](https://raw.githubusercontent.com/googolmo/Leveldb-Android/master/lib/src/main/jniLibs/armeabi/libleveldbjni.so) to jniLibs/armeabi/libleveldbjni.so 45 | save [armeabi-v7a/libleveldbjni.so](https://raw.githubusercontent.com/googolmo/Leveldb-Android/master/lib/src/main/jniLibs/armeabi-v7a/libleveldbjni.so) to jniLibs/armeabi-v7a/libleveldbjni.so 46 | 47 | * local jar and local so 48 | 49 | save [jar](https://drone.io/github.com/googolmo/Leveldb-Android/files/lib/build/libs/lib-1.0.0.jar) to libs/ 50 | 51 | ### Usage (TODO) 52 | 53 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Settings specified in this file will override any Gradle settings 5 | # configured through the IDE. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m 13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 14 | 15 | # When configured, Gradle will run in incubating parallel mode. 16 | # This option should only be used with decoupled projects. More details, visit 17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 18 | # org.gradle.parallel=true 19 | 20 | VERSION_NAME=1.0.1 21 | VERSION_CODE=2 22 | GROUP=im.amomo.leveldb 23 | 24 | POM_DESCRIPTION=Port leveldb to Android 25 | POM_URL=https://github.com/googolmo/Leveldb-Android 26 | POM_SCM_URL=https://github.com/googolmo/Leveldb-Android 27 | POM_SCM_CONNECTION=scm:git@github.com:googolmo/Leveldb-Android.git 28 | POM_SCM_DEV_CONNECTION=scm:git@github.com:googolmo/Leveldb-Android.git 29 | POM_LICENCE_NAME=GNU GENERAL PUBLIC LICENSE Version 2 30 | POM_LICENCE_URL=https://raw.github.com/googolmo/Leveldb-Android/master/LICENSE.md 31 | POM_LICENCE_DIST=repo 32 | POM_DEVELOPER_ID=googolmo 33 | POM_DEVELOPER_NAME=Momo Wang 34 | -------------------------------------------------------------------------------- /lib/src/main/jni-src/jni/Android.mk: -------------------------------------------------------------------------------- 1 | LOCAL_PATH := ${call my-dir} 2 | 3 | include $(CLEAR_VARS) 4 | 5 | LOCAL_MODULE := leveldbjni 6 | LOCAL_C_INCLUDES := $(LOCAL_PATH)/leveldb/include 7 | LOCAL_CPP_EXTENSION := .cc 8 | LOCAL_CFLAGS := -DLEVELDB_PLATFORM_ANDROID -std=gnu++0x 9 | LOCAL_SRC_FILES := leveldbjni.cc 10 | LOCAL_STATIC_LIBRARIES += leveldb 11 | LOCAL_LDLIBS += -llog -ldl 12 | 13 | include $(BUILD_SHARED_LIBRARY) 14 | 15 | include $(CLEAR_VARS) 16 | LOCAL_MODULE := leveldb 17 | LOCAL_CFLAGS := -D_REENTRANT -DOS_ANDROID -DLEVELDB_PLATFORM_POSIX -DNDEBUG -DSNAPPY 18 | LOCAL_CPP_EXTENSION := .cc 19 | LOCAL_C_INCLUDES := $(LOCAL_PATH)/leveldb $(LOCAL_PATH)/leveldb/include $(LOCAL_PATH)/snappy 20 | LOCAL_SRC_FILES := leveldb/db/builder.cc leveldb/db/c.cc leveldb/db/db_impl.cc leveldb/db/db_iter.cc leveldb/db/dbformat.cc leveldb/db/filename.cc leveldb/db/log_reader.cc leveldb/db/log_writer.cc leveldb/db/memtable.cc leveldb/db/repair.cc leveldb/db/table_cache.cc leveldb/db/version_edit.cc leveldb/db/version_set.cc leveldb/db/write_batch.cc leveldb/table/block.cc leveldb/table/block_builder.cc leveldb/table/filter_block.cc leveldb/table/format.cc leveldb/table/iterator.cc leveldb/table/merger.cc leveldb/table/table.cc leveldb/table/table_builder.cc leveldb/table/two_level_iterator.cc leveldb/util/arena.cc leveldb/util/bloom.cc leveldb/util/cache.cc leveldb/util/coding.cc leveldb/util/comparator.cc leveldb/util/crc32c.cc leveldb/util/env.cc leveldb/util/env_posix.cc leveldb/util/filter_policy.cc leveldb/util/hash.cc leveldb/util/histogram.cc leveldb/util/logging.cc leveldb/util/options.cc leveldb/util/status.cc leveldb/port/port_posix.cc 21 | LOCAL_STATIC_LIBRARIES += snappy 22 | 23 | include $(BUILD_STATIC_LIBRARY) 24 | 25 | 26 | include $(CLEAR_VARS) 27 | LOCAL_MODULE := snappy 28 | LOCAL_CPP_EXTENSION := .cc 29 | LOCAL_SRC_FILES := snappy/snappy.cc snappy/snappy-c.cc snappy/snappy-sinksource.cc 30 | 31 | include $(BUILD_STATIC_LIBRARY) 32 | 33 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /sample/src/main/java/im/amomo/leveldb/sample/MainActivity.java: -------------------------------------------------------------------------------- 1 | package im.amomo.leveldb.sample; 2 | 3 | import android.app.Activity; 4 | import android.app.ActionBar; 5 | import android.app.Fragment; 6 | import android.content.Context; 7 | import android.os.Bundle; 8 | import android.os.Environment; 9 | import android.os.SystemClock; 10 | import android.util.Log; 11 | import android.view.LayoutInflater; 12 | import android.view.Menu; 13 | import android.view.MenuItem; 14 | import android.view.View; 15 | import android.view.ViewGroup; 16 | import android.os.Build; 17 | import android.widget.TextView; 18 | import im.amomo.leveldb.DBFactory; 19 | import im.amomo.leveldb.LevelDB; 20 | 21 | import java.io.File; 22 | import java.io.IOException; 23 | 24 | 25 | public class MainActivity extends Activity { 26 | 27 | protected static final String DB_KEY = "hello"; 28 | 29 | @Override 30 | protected void onCreate(Bundle savedInstanceState) { 31 | super.onCreate(savedInstanceState); 32 | setContentView(R.layout.activity_main); 33 | if (savedInstanceState == null) { 34 | getFragmentManager().beginTransaction() 35 | .add(R.id.container, new PlaceholderFragment()) 36 | .commit(); 37 | } 38 | } 39 | 40 | 41 | @Override 42 | public boolean onCreateOptionsMenu(Menu menu) { 43 | 44 | // Inflate the menu; this adds items to the action bar if it is present. 45 | getMenuInflater().inflate(R.menu.main, menu); 46 | return true; 47 | } 48 | 49 | @Override 50 | public boolean onOptionsItemSelected(MenuItem item) { 51 | // Handle action bar item clicks here. The action bar will 52 | // automatically handle clicks on the Home/Up button, so long 53 | // as you specify a parent activity in AndroidManifest.xml. 54 | int id = item.getItemId(); 55 | if (id == R.id.action_settings) { 56 | return true; 57 | } 58 | return super.onOptionsItemSelected(item); 59 | } 60 | 61 | /** 62 | * A placeholder fragment containing a simple view. 63 | */ 64 | public static class PlaceholderFragment extends Fragment { 65 | private TextView mTv; 66 | 67 | public PlaceholderFragment() { 68 | } 69 | 70 | @Override 71 | public View onCreateView(LayoutInflater inflater, ViewGroup container, 72 | Bundle savedInstanceState) { 73 | View rootView = inflater.inflate(R.layout.fragment_main, container, false); 74 | return rootView; 75 | } 76 | 77 | @Override 78 | public void onViewCreated(View view, Bundle savedInstanceState) { 79 | super.onViewCreated(view, savedInstanceState); 80 | mTv = (TextView) view.findViewById(R.id.hello); 81 | LevelDB db = DBFactory.open(getActivity(), "hobbits1"); 82 | long start = System.currentTimeMillis(); 83 | String value = null; 84 | if (db.exists(DB_KEY)) { 85 | value = String.valueOf(db.getLong(DB_KEY)); 86 | } 87 | if (value == null) { 88 | db.put(DB_KEY, 123l); 89 | } else { 90 | mTv.setText(value); 91 | } 92 | db.close(); 93 | long end = System.currentTimeMillis(); 94 | Log.d(MainActivity.class.getName(), "total=" + (end - start)); 95 | } 96 | 97 | 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /lib/src/androidTest/java/im/amomo/leveldb/TestDB.java: -------------------------------------------------------------------------------- 1 | package im.amomo.leveldb; 2 | 3 | import android.content.Context; 4 | import android.test.AndroidTestCase; 5 | 6 | /** 7 | * Created by GoogolMo on 3/26/14. 8 | */ 9 | public class TestDB extends AndroidTestCase { 10 | private static final String DB_NAME = "test_db"; 11 | 12 | protected LevelDB db; 13 | 14 | public void testOpenDB() throws Exception { 15 | db = DBFactory.open(getContext(), DB_NAME); 16 | assertNotNull(db); 17 | db.close(); 18 | } 19 | 20 | public void testByteArray() throws Exception { 21 | db = DBFactory.open(getContext(), DB_NAME); 22 | db.put("test_bytes", "test_byte".getBytes()); 23 | assertEquals(new String(db.get("test_bytes")), "test_byte"); 24 | db.close(); 25 | } 26 | 27 | public void testString() throws Exception { 28 | db = DBFactory.open(getContext(), DB_NAME); 29 | db.put("test_string", "test_string"); 30 | assertEquals(db.getString("test_string"), "test_string"); 31 | db.close(); 32 | } 33 | 34 | public void testLong() throws Exception { 35 | db = DBFactory.open(getContext(), DB_NAME); 36 | db.put("test_long", 123456l); 37 | assertEquals(db.getLong("test_long"), 123456l); 38 | db.close(); 39 | } 40 | 41 | public void testShort() throws Exception { 42 | db = DBFactory.open(getContext(), DB_NAME); 43 | db.put("test_short", Short.MIN_VALUE); 44 | assertEquals(db.getShort("test_short"), Short.MIN_VALUE); 45 | db.close(); 46 | } 47 | 48 | public void testInt() throws Exception { 49 | db = DBFactory.open(getContext(), DB_NAME); 50 | db.put("test_int", Integer.MAX_VALUE); 51 | assertEquals(db.getInt("test_int"), Integer.MAX_VALUE); 52 | db.close(); 53 | } 54 | 55 | public void testDouble() throws Exception { 56 | db = DBFactory.open(getContext(), DB_NAME); 57 | db.put("test_double", 1.12345d); 58 | System.out.println(db.getDouble("test_double")); 59 | assertEquals(db.getDouble("test_double"), 1.12345d); 60 | db.close(); 61 | } 62 | 63 | public void testFloat() throws Exception { 64 | db = DBFactory.open(getContext(), DB_NAME); 65 | db.put("test_float", 1.12345f); 66 | assertEquals(db.getFloat("test_float"), 1.12345f); 67 | db.close(); 68 | } 69 | 70 | public void testBoolean() throws Exception { 71 | db = DBFactory.open(getContext(), DB_NAME); 72 | db.put("test_boolean", true); 73 | assertEquals(db.getBoolean("test_boolean"), true); 74 | db.close(); 75 | } 76 | 77 | public void test1000() throws Exception { 78 | db = DBFactory.open(getContext(), DB_NAME); 79 | for (int i = 0; i < 100; i ++) { 80 | db.put("test_" + i, i * 100); 81 | } 82 | assertNotNull(db); 83 | db.close(); 84 | } 85 | 86 | public void testExists() throws Exception { 87 | db = DBFactory.open(getContext(), DB_NAME); 88 | db.put("key_exists", "<(= ̄▽ ̄=)>"); 89 | assertTrue(db.exists("key_exists")); 90 | db.close(); 91 | } 92 | 93 | public void testDelete() throws Exception { 94 | db = DBFactory.open(getContext(), DB_NAME); 95 | db.put("key_delete", "<(= ̄▽ ̄=)>"); 96 | db.delete("key_delete"); 97 | assertFalse(db.exists("key_delete")); 98 | db.close(); 99 | } 100 | 101 | public void testDestroy() throws Exception { 102 | db = DBFactory.open(getContext(), DB_NAME); 103 | db.close(); 104 | db.destroy(); 105 | } 106 | 107 | 108 | @Override 109 | protected void setUp() throws Exception { 110 | super.setUp(); 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # For Cygwin, ensure paths are in UNIX format before anything is touched. 46 | if $cygwin ; then 47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 48 | fi 49 | 50 | # Attempt to set APP_HOME 51 | # Resolve links: $0 may be a link 52 | PRG="$0" 53 | # Need this for relative symlinks. 54 | while [ -h "$PRG" ] ; do 55 | ls=`ls -ld "$PRG"` 56 | link=`expr "$ls" : '.*-> \(.*\)$'` 57 | if expr "$link" : '/.*' > /dev/null; then 58 | PRG="$link" 59 | else 60 | PRG=`dirname "$PRG"`"/$link" 61 | fi 62 | done 63 | SAVED="`pwd`" 64 | cd "`dirname \"$PRG\"`/" >&- 65 | APP_HOME="`pwd -P`" 66 | cd "$SAVED" >&- 67 | 68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 69 | 70 | # Determine the Java command to use to start the JVM. 71 | if [ -n "$JAVA_HOME" ] ; then 72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 73 | # IBM's JDK on AIX uses strange locations for the executables 74 | JAVACMD="$JAVA_HOME/jre/sh/java" 75 | else 76 | JAVACMD="$JAVA_HOME/bin/java" 77 | fi 78 | if [ ! -x "$JAVACMD" ] ; then 79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 80 | 81 | Please set the JAVA_HOME variable in your environment to match the 82 | location of your Java installation." 83 | fi 84 | else 85 | JAVACMD="java" 86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 87 | 88 | Please set the JAVA_HOME variable in your environment to match the 89 | location of your Java installation." 90 | fi 91 | 92 | # Increase the maximum file descriptors if we can. 93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 94 | MAX_FD_LIMIT=`ulimit -H -n` 95 | if [ $? -eq 0 ] ; then 96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 97 | MAX_FD="$MAX_FD_LIMIT" 98 | fi 99 | ulimit -n $MAX_FD 100 | if [ $? -ne 0 ] ; then 101 | warn "Could not set maximum file descriptor limit: $MAX_FD" 102 | fi 103 | else 104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 105 | fi 106 | fi 107 | 108 | # For Darwin, add options to specify how the application appears in the dock 109 | if $darwin; then 110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 111 | fi 112 | 113 | # For Cygwin, switch paths to Windows format before running java 114 | if $cygwin ; then 115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 158 | function splitJvmOpts() { 159 | JVM_OPTS=("$@") 160 | } 161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 163 | 164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 165 | -------------------------------------------------------------------------------- /lib/src/main/java/im/amomo/leveldb/LevelDB.java: -------------------------------------------------------------------------------- 1 | package im.amomo.leveldb; 2 | 3 | import android.text.TextUtils; 4 | import android.util.Log; 5 | 6 | import java.io.File; 7 | 8 | /** 9 | * Created by GoogolMo on 3/13/14. 10 | */ 11 | public class LevelDB { 12 | 13 | 14 | private final String mPath; 15 | 16 | public LevelDB(File path) throws LevelDBException { 17 | if (path == null) { 18 | throw new NullPointerException(); 19 | } 20 | mPath = path.getAbsolutePath(); 21 | nativeOpen(mPath); 22 | } 23 | 24 | public LevelDB(String path) throws LevelDBException { 25 | if (TextUtils.isEmpty(path)) { 26 | throw new NullPointerException(); 27 | } 28 | mPath = path; 29 | nativeOpen(mPath); 30 | } 31 | 32 | 33 | public void close() { 34 | nativeClose(); 35 | } 36 | 37 | public void put(String key, byte[] value) throws LevelDBException { 38 | if (TextUtils.isEmpty(key)) { 39 | throw new NullPointerException("key can not be null"); 40 | } 41 | if (value == null) { 42 | throw new NullPointerException("value can not be null"); 43 | } 44 | 45 | nativePut(key, value); 46 | 47 | } 48 | 49 | public void put(String key, String value) throws LevelDBException { 50 | if (TextUtils.isEmpty(key)) { 51 | throw new NullPointerException("key can not be null"); 52 | } 53 | 54 | if (value == null) { 55 | throw new NullPointerException("value can not be null"); 56 | } 57 | 58 | nativePutString(key, value); 59 | } 60 | 61 | public void put(String key, long value) throws LevelDBException { 62 | if (TextUtils.isEmpty(key)) { 63 | throw new NullPointerException("key can not be null"); 64 | } 65 | 66 | nativePutLong(key, value); 67 | } 68 | 69 | public void put(String key, int value) throws LevelDBException { 70 | if (TextUtils.isEmpty(key)) { 71 | throw new NullPointerException("key can not be null"); 72 | } 73 | 74 | nativePutInt(key, value); 75 | } 76 | 77 | public void put(String key, short value) throws LevelDBException { 78 | if (TextUtils.isEmpty(key)) { 79 | throw new NullPointerException("key can not be null"); 80 | } 81 | 82 | nativePutShort(key, value); 83 | } 84 | 85 | public void put(String key, double value) throws LevelDBException { 86 | if (TextUtils.isEmpty(key)) { 87 | throw new NullPointerException("key can not be null"); 88 | } 89 | 90 | nativePutDouble(key, value); 91 | } 92 | 93 | public void put(String key, float value) throws LevelDBException { 94 | if (TextUtils.isEmpty(key)) { 95 | throw new NullPointerException("key can not be null"); 96 | } 97 | 98 | nativePutFloat(key, value); 99 | } 100 | 101 | public void put(String key, boolean value) throws LevelDBException { 102 | if (TextUtils.isEmpty(key)) { 103 | throw new NullPointerException("key can not be null"); 104 | } 105 | nativePutBoolean(key, value); 106 | } 107 | 108 | public byte[] get(String key) throws LevelDBException { 109 | if (TextUtils.isEmpty(key)) { 110 | throw new NullPointerException("key can not be null"); 111 | } 112 | if (nativeExists(key)) { 113 | return nativeGet(key); 114 | } 115 | return null; 116 | } 117 | 118 | public String getString(String key) throws LevelDBException { 119 | if (TextUtils.isEmpty(key)) { 120 | throw new NullPointerException("key can not be null"); 121 | } 122 | if (nativeExists(key)) { 123 | return nativeGetString(key); 124 | } 125 | return null; 126 | } 127 | 128 | public long getLong(String key) throws LevelDBException { 129 | if (TextUtils.isEmpty(key)) { 130 | throw new NullPointerException("key can not be null"); 131 | } 132 | return nativeGetLong(key); 133 | } 134 | 135 | public int getInt(String key) throws LevelDBException { 136 | if (TextUtils.isEmpty(key)) { 137 | throw new NullPointerException("key can not be null"); 138 | } 139 | return nativeGetInt(key); 140 | } 141 | 142 | public short getShort(String key) throws LevelDBException { 143 | if (TextUtils.isEmpty(key)) { 144 | throw new NullPointerException("key can not be null"); 145 | } 146 | return nativeGetShort(key); 147 | } 148 | 149 | public double getDouble(String key) throws LevelDBException { 150 | if (TextUtils.isEmpty(key)) { 151 | throw new NullPointerException("key can not be null"); 152 | } 153 | return nativeGetDouble(key); 154 | } 155 | 156 | public float getFloat(String key) throws LevelDBException { 157 | if (TextUtils.isEmpty(key)) { 158 | throw new NullPointerException("key can not be null"); 159 | } 160 | return nativeGetFloat(key); 161 | } 162 | 163 | public boolean getBoolean(String key) throws LevelDBException { 164 | if (TextUtils.isEmpty(key)) { 165 | throw new NullPointerException("key can not be null"); 166 | } 167 | return nativeGetBoolean(key); 168 | } 169 | 170 | public void delete(String key) throws LevelDBException { 171 | if (TextUtils.isEmpty(key)) { 172 | throw new NullPointerException("key can not be null"); 173 | } 174 | 175 | nativeDelete(key); 176 | } 177 | 178 | public void destroy() throws LevelDBException{ 179 | destroy(mPath); 180 | } 181 | 182 | public boolean exists(String key) throws LevelDBException { 183 | if (TextUtils.isEmpty(key)) { 184 | throw new NullPointerException("key can not be null"); 185 | } 186 | return nativeExists(key); 187 | } 188 | 189 | public static void destroy(String path) throws LevelDBException{ 190 | if (TextUtils.isEmpty(path)) { 191 | throw new NullPointerException("path can not be null"); 192 | } 193 | nativeDestroy(path); 194 | } 195 | 196 | private native void nativeOpen(String dbpath); 197 | 198 | private native void nativeClose(); 199 | 200 | private native void nativePut(String key, byte[] value); 201 | 202 | private native void nativePutString(String key, String value); 203 | 204 | private native void nativePutLong(String key, long value); 205 | 206 | private native void nativePutInt(String key, int value); 207 | 208 | private native void nativePutShort(String key, short value); 209 | 210 | private native void nativePutDouble(String key, double value); 211 | 212 | private native void nativePutFloat(String key, float value); 213 | 214 | private native void nativePutBoolean(String key, boolean value); 215 | 216 | private native byte[] nativeGet(String key); 217 | 218 | private native String nativeGetString(String key); 219 | 220 | private native long nativeGetLong(String key); 221 | 222 | private native int nativeGetInt(String key); 223 | 224 | private native short nativeGetShort(String key); 225 | 226 | private native double nativeGetDouble(String key); 227 | 228 | private native float nativeGetFloat(String key); 229 | 230 | private native boolean nativeGetBoolean(String key); 231 | 232 | private native void nativeDelete(String key); 233 | 234 | private native boolean nativeExists(String key); 235 | 236 | private static native void nativeDestroy(String dbpath); 237 | 238 | static { 239 | Log.d(LevelDB.class.getSimpleName(), "loadjni"); 240 | System.loadLibrary("leveldbjni"); 241 | } 242 | 243 | } 244 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | {description} 294 | Copyright (C) {year} {fullname} 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | {signature of Ty Coon}, 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /lib/src/main/jni-src/jni/leveldbjni.cc: -------------------------------------------------------------------------------- 1 | #include "leveldbjni.h" 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | int register_im_amomo_leveldb_LevelDB(JNIEnv *env); 8 | 9 | leveldb::DB* db; 10 | bool isDBOpen; 11 | char* dbPath; 12 | 13 | jint throwException(JNIEnv* env, const char* msg) { 14 | const char* exceptionClass = "im/amomo/leveldb/LevelDBException"; 15 | 16 | jclass clazz = env->FindClass(exceptionClass); 17 | if (!clazz) { 18 | LOGE("Can't find exception class %s", exceptionClass); 19 | return -1; 20 | } 21 | 22 | return env->ThrowNew(clazz, msg); 23 | } 24 | 25 | void releaseDB() { 26 | delete db; 27 | isDBOpen = false; 28 | free(dbPath); 29 | dbPath = NULL; 30 | } 31 | 32 | int JNI_OnLoad(JavaVM* vm, void *reserved) { 33 | JNIEnv* env = NULL; 34 | if (vm->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6) != JNI_OK) { 35 | return -1; 36 | } 37 | releaseDB(); 38 | 39 | register_im_amomo_leveldb_LevelDB(env); 40 | 41 | return JNI_VERSION_1_6; 42 | } 43 | 44 | void JNI_OnUnload(JavaVM* vm, void* reserved) { 45 | 46 | delete db; 47 | isDBOpen = false; 48 | free(dbPath); 49 | dbPath = NULL; 50 | } 51 | 52 | void nativeOpen(JNIEnv* env, jclass clazz, jstring dbpath) { 53 | const char *path = env->GetStringUTFChars(dbpath, 0); 54 | 55 | if (isDBOpen) { 56 | if (NULL != dbPath && 0 != strcmp(dbPath, path)) { 57 | throwException(env, "Your database is still open, please close it before"); 58 | } else { 59 | LOGI("database was already open %s", path); 60 | } 61 | 62 | env->ReleaseStringUTFChars(dbpath, path); 63 | } 64 | leveldb::Options options; 65 | options.create_if_missing = true; 66 | options.compression = leveldb::kSnappyCompression; 67 | leveldb::Status status = leveldb::DB::Open(options, path, &db); 68 | 69 | if (!status.ok()) { 70 | LOGE("Failed to open database"); 71 | releaseDB(); 72 | std::string err("Failed to open/create database:" + status.ToString()); 73 | env->ReleaseStringUTFChars(dbpath, path); 74 | throwException(env, err.c_str()); 75 | } else { 76 | isDBOpen = true; 77 | if ((dbPath = strdup(path)) != NULL) { 78 | env->ReleaseStringUTFChars(dbpath, path); 79 | LOGI("Opened databse"); 80 | } else { 81 | env->ReleaseStringUTFChars(dbpath, path); 82 | throwException(env, "OutOfMemory when saving the database name"); 83 | } 84 | } 85 | } 86 | 87 | void nativeClose(JNIEnv* env, jclass clazz) { 88 | if (isDBOpen) { 89 | releaseDB(); 90 | } else { 91 | throwException(env, "Database was already closed"); 92 | } 93 | } 94 | 95 | static void nativeDestroy(JNIEnv* env, 96 | jclass clazz, 97 | jstring dbpath) { 98 | const char* path = env->GetStringUTFChars(dbpath, 0); 99 | 100 | leveldb::Options options; 101 | options.create_if_missing = true; 102 | leveldb::Status status = DestroyDB(path, options); 103 | 104 | env->ReleaseStringUTFChars(dbpath, path); 105 | 106 | if (!status.ok()) { 107 | std::string err("Failed to destroy database: " + status.ToString()); 108 | throwException(env, err.c_str()); 109 | } 110 | } 111 | 112 | void nativeDelete(JNIEnv* env, jclass clazz, jstring jkey) { 113 | 114 | if (!isDBOpen) { 115 | throwException(env, "Database is not open"); 116 | return; 117 | } 118 | 119 | const char* key = env->GetStringUTFChars(jkey, 0); 120 | 121 | leveldb::Status status = db->Delete(leveldb::WriteOptions(), key); 122 | 123 | env->ReleaseStringUTFChars(jkey, key); 124 | 125 | if (!status.ok()) { 126 | std::string err("Failed to delete: " + status.ToString()); 127 | throwException(env, err.c_str()); 128 | } 129 | } 130 | 131 | 132 | void nativePutString(JNIEnv* env, jclass clazz, jstring jkey, jstring jval) { 133 | 134 | LOGI("Putting a string"); 135 | 136 | if (!isDBOpen) { 137 | throwException(env, "Database is not open"); 138 | return; 139 | } 140 | 141 | const char* key = env->GetStringUTFChars(jkey, 0); 142 | const char* value = env->GetStringUTFChars(jval, 0); 143 | 144 | leveldb::Status status = db->Put(leveldb::WriteOptions(), key, value); 145 | 146 | env->ReleaseStringUTFChars(jval, value); 147 | env->ReleaseStringUTFChars(jkey, key); 148 | 149 | if (!status.ok()) { 150 | std::string err("Failed to put a String: " + status.ToString()); 151 | throwException(env, err.c_str()); 152 | } 153 | } 154 | 155 | void nativePut(JNIEnv* env, jclass clazz, jstring jkey, jbyteArray arr) { 156 | LOGI("Putting a Serializable"); 157 | if (!isDBOpen) { 158 | throwException(env, "Database is not open"); 159 | return; 160 | } 161 | 162 | int len = env->GetArrayLength(arr); 163 | jbyte* data = (jbyte*)env->GetPrimitiveArrayCritical(arr, 0); 164 | 165 | if (data == NULL) { 166 | throwException(env, "OutOfMemory when trying to get bytes array for Serializable"); 167 | return; 168 | } 169 | 170 | const char* key = env->GetStringUTFChars(jkey, 0); 171 | leveldb::Slice value = leveldb::Slice(reinterpret_cast(data), len); 172 | 173 | leveldb::Status status = db->Put(leveldb::WriteOptions(), key, value); 174 | 175 | env->ReleasePrimitiveArrayCritical(arr, data, 0); 176 | env->ReleaseStringUTFChars(jkey, key); 177 | 178 | if (!status.ok()) { 179 | std::string err("Failed to put a Serializable: " + status.ToString()); 180 | throwException(env, err.c_str()); 181 | } 182 | 183 | } 184 | 185 | void nativePutLong(JNIEnv* env, jclass clazz, jstring jkey, jlong jval) { 186 | LOGI("Putting a long "); 187 | 188 | if (!isDBOpen) { 189 | throwException(env, "Database is not open"); 190 | return; 191 | } 192 | 193 | const char* key = env->GetStringUTFChars(jkey, 0); 194 | leveldb::Slice value = leveldb::Slice((char*) &jval, sizeof(jlong)); 195 | 196 | leveldb::Status status = db->Put(leveldb::WriteOptions(), key, value); 197 | 198 | env->ReleaseStringUTFChars(jkey, key); 199 | 200 | if (!status.ok()) { 201 | std::string err("Failed to put a long: " + status.ToString()); 202 | throwException(env, err.c_str()); 203 | } 204 | } 205 | 206 | void nativePutInt(JNIEnv* env, jclass clazz, jstring jkey, jint jval) { 207 | LOGI("Putting an int"); 208 | 209 | if (!isDBOpen) { 210 | throwException(env, "Database is not open"); 211 | return; 212 | } 213 | 214 | const char* key = env->GetStringUTFChars(jkey, 0); 215 | leveldb::Slice value = leveldb::Slice ((char*)& jval, sizeof(jint)); 216 | 217 | leveldb::Status status = db->Put(leveldb::WriteOptions(), key, value); 218 | 219 | env->ReleaseStringUTFChars(jkey, key); 220 | 221 | if (!status.ok()) { 222 | std::string err("Failed to put an int: " + status.ToString()); 223 | throwException(env, err.c_str()); 224 | } 225 | } 226 | 227 | void nativePutShort(JNIEnv* env, jclass clazz, jstring jkey, jshort jval) { 228 | LOGI("Putting an short"); 229 | 230 | if (!isDBOpen) { 231 | throwException(env, "Database is not open"); 232 | return; 233 | } 234 | 235 | const char* key = env->GetStringUTFChars(jkey, 0); 236 | leveldb::Slice value = leveldb::Slice ((char*)& jval, sizeof(jshort)); 237 | 238 | leveldb::Status status = db->Put(leveldb::WriteOptions(), key, value); 239 | 240 | env->ReleaseStringUTFChars(jkey, key); 241 | 242 | if (!status.ok()) { 243 | std::string err("Failed to put an short: " + status.ToString()); 244 | throwException(env, err.c_str()); 245 | } 246 | } 247 | 248 | void nativePutBoolean(JNIEnv* env, jclass clazz, jstring jkey, jboolean jval) { 249 | LOGI("Putting an boolean"); 250 | 251 | if (!isDBOpen) { 252 | throwException(env, "Database is not open"); 253 | return; 254 | } 255 | 256 | const char* key = env->GetStringUTFChars(jkey, 0); 257 | leveldb::Slice value = leveldb::Slice ((char*)& jval, sizeof(jboolean)); 258 | 259 | leveldb::Status status = db->Put(leveldb::WriteOptions(), key, value); 260 | 261 | env->ReleaseStringUTFChars(jkey, key); 262 | 263 | if (!status.ok()) { 264 | std::string err("Failed to put an boolean: " + status.ToString()); 265 | throwException(env, err.c_str()); 266 | } 267 | } 268 | 269 | void nativePutDouble(JNIEnv* env, jclass clazz, jstring jkey, jdouble jval) { 270 | LOGI("Putting an double"); 271 | 272 | if (!isDBOpen) { 273 | throwException(env, "Database is not open"); 274 | return; 275 | } 276 | 277 | const char* key = env->GetStringUTFChars(jkey, 0); 278 | 279 | std::ostringstream oss; 280 | oss << std::setprecision(17) << jval; 281 | std::string value = oss.str(); 282 | 283 | leveldb::Status status = db->Put(leveldb::WriteOptions(), key, value); 284 | 285 | env->ReleaseStringUTFChars(jkey, key); 286 | 287 | if (!status.ok()) { 288 | std::string err("Failed to put an double: " + status.ToString()); 289 | throwException(env, err.c_str()); 290 | } 291 | } 292 | 293 | void nativePutFloat(JNIEnv* env, jclass clazz, jstring jkey, jfloat jval) { 294 | LOGI("Putting an float"); 295 | 296 | if (!isDBOpen) { 297 | throwException(env, "Database is not open"); 298 | return; 299 | } 300 | 301 | const char* key = env->GetStringUTFChars(jkey, 0); 302 | 303 | std::ostringstream oss; 304 | oss << std::setprecision(16) << jval; 305 | std::string value = oss.str(); 306 | 307 | leveldb::Status status = db->Put(leveldb::WriteOptions(), key, value); 308 | 309 | env->ReleaseStringUTFChars(jkey, key); 310 | 311 | if (!status.ok()) { 312 | std::string err("Failed to put an float: " + status.ToString()); 313 | throwException(env, err.c_str()); 314 | } 315 | } 316 | 317 | jstring nativeGetString(JNIEnv* env, jclass clazz, jstring jkey) { 318 | LOGI("Getting a String"); 319 | 320 | if (!isDBOpen) { 321 | throwException(env, "Database is not open"); 322 | return NULL; 323 | } 324 | 325 | const char* key = env->GetStringUTFChars(jkey, 0); 326 | std::string value; 327 | leveldb::Status status = db->Get(leveldb::ReadOptions(), key, &value); 328 | 329 | env->ReleaseStringUTFChars(jkey, key); 330 | 331 | if (status.ok()) { 332 | return env->NewStringUTF(value.c_str()); 333 | } else { 334 | std::string err("Failed to get a String: " + status.ToString()); 335 | throwException(env, err.c_str()); 336 | return NULL; 337 | } 338 | } 339 | 340 | jlong nativeGetLong(JNIEnv* env, jclass clazz, jstring jkey) { 341 | LOGI("Getting a Long"); 342 | 343 | if (!isDBOpen) { 344 | throwException(env, "Database is not open"); 345 | } 346 | 347 | const char* key = env->GetStringUTFChars(jkey, 0); 348 | std::string data; 349 | leveldb::Status status = db->Get(leveldb::ReadOptions(), key, &data); 350 | 351 | env->ReleaseStringUTFChars(jkey, key); 352 | 353 | if (status.ok()) { 354 | if (8 == data.length()) { 355 | const char* bytes = data.data(); 356 | long ret = 0; 357 | 358 | ret = bytes[7]; 359 | ret = (ret << 8) + (unsigned char)bytes[6]; 360 | ret = (ret << 8) + (unsigned char)bytes[5]; 361 | ret = (ret << 8) + (unsigned char)bytes[4]; 362 | ret = (ret << 8) + (unsigned char)bytes[3]; 363 | ret = (ret << 8) + (unsigned char)bytes[2]; 364 | ret = (ret << 8) + (unsigned char)bytes[1]; 365 | ret = (ret << 8) + (unsigned char)bytes[0]; 366 | return ret; 367 | } else { 368 | throwException(env, "Failed to get a Long"); 369 | } 370 | } else { 371 | std::string err("Failed to get a Long: " + status.ToString()); 372 | throwException(env, err.c_str()); 373 | } 374 | } 375 | 376 | jint nativeGetInt(JNIEnv* env, jclass clazz, jstring jkey) { 377 | LOGI("Getting a Int"); 378 | 379 | if (!isDBOpen) { 380 | throwException(env, "Database is not open"); 381 | } 382 | 383 | const char* key = env->GetStringUTFChars(jkey, 0); 384 | std::string data; 385 | leveldb::Status status = db->Get(leveldb::ReadOptions(), key, &data); 386 | 387 | env->ReleaseStringUTFChars(jkey, key); 388 | 389 | if (status.ok()) { 390 | if (4 == data.length()) { 391 | const char* bytes = data.data(); 392 | long ret = 0; 393 | 394 | ret = bytes[3]; 395 | ret = (ret << 8) + (unsigned char)bytes[2]; 396 | ret = (ret << 8) + (unsigned char)bytes[1]; 397 | ret = (ret << 8) + (unsigned char)bytes[0]; 398 | return ret; 399 | } else { 400 | throwException(env, "Failed to get a Int"); 401 | } 402 | } else { 403 | std::string err("Failed to get a Int: " + status.ToString()); 404 | throwException(env, err.c_str()); 405 | } 406 | } 407 | 408 | jdouble nativeGetDouble(JNIEnv* env, jclass clazz, jstring jkey) { 409 | LOGI("Getting a Double"); 410 | 411 | if (!isDBOpen) { 412 | throwException(env, "Database is not open"); 413 | } 414 | 415 | const char* key = env->GetStringUTFChars(jkey, 0); 416 | std::string data; 417 | leveldb::Status status = db->Get(leveldb::ReadOptions(), key, &data); 418 | 419 | env->ReleaseStringUTFChars(jkey, key); 420 | 421 | if (status.ok()) { 422 | double d = atof(data.c_str()); 423 | return d; 424 | } else { 425 | std::string err("Failed to get a Double: " + status.ToString()); 426 | throwException(env, err.c_str()); 427 | } 428 | } 429 | 430 | jfloat nativeGetFloat(JNIEnv* env, jclass clazz, jstring jkey) { 431 | LOGI("Getting a Float"); 432 | 433 | if (!isDBOpen) { 434 | throwException(env, "Database is not open"); 435 | } 436 | 437 | const char* key = env->GetStringUTFChars(jkey, 0); 438 | std::string data; 439 | leveldb::Status status = db->Get(leveldb::ReadOptions(), key, &data); 440 | 441 | env->ReleaseStringUTFChars(jkey, key); 442 | 443 | if (status.ok()) { 444 | float f = atof(data.c_str()); 445 | return f; 446 | } else { 447 | std::string err("Failed to get a Short: " + status.ToString()); 448 | throwException(env, err.c_str()); 449 | } 450 | } 451 | 452 | jshort nativeGetShort(JNIEnv* env, jclass clazz, jstring jkey) { 453 | LOGI("Getting a Short"); 454 | 455 | if (!isDBOpen) { 456 | throwException(env, "Database is not open"); 457 | } 458 | 459 | const char* key = env->GetStringUTFChars(jkey, 0); 460 | std::string data; 461 | leveldb::Status status = db->Get(leveldb::ReadOptions(), key, &data); 462 | 463 | env->ReleaseStringUTFChars(jkey, key); 464 | 465 | if (status.ok()) { 466 | if (2 == data.length()) { 467 | const char* bytes = data.data(); 468 | short ret = 0; 469 | ret = bytes[1]; 470 | ret = (ret << 8) + bytes[0]; 471 | return ret; 472 | } else { 473 | throwException(env, "Failed to get a Short"); 474 | } 475 | } else { 476 | std::string err("Failed to get a Short: " + status.ToString()); 477 | throwException(env, err.c_str()); 478 | } 479 | } 480 | 481 | jboolean nativeGetBoolean(JNIEnv* env, jclass clazz, jstring jkey) { 482 | LOGI("Getting a Boolean"); 483 | 484 | if (!isDBOpen) { 485 | throwException(env, "Database is not open"); 486 | } 487 | 488 | const char* key = env->GetStringUTFChars(jkey, 0); 489 | std::string data; 490 | leveldb::Status status = db->Get(leveldb::ReadOptions(), key, &data); 491 | 492 | env->ReleaseStringUTFChars(jkey, key); 493 | 494 | if (status.ok()) { 495 | if (1 == data.length()) { 496 | return data.data()[0]; 497 | } else { 498 | throwException(env, "Failed to get a Boolean"); 499 | } 500 | } else { 501 | std::string err("Failed to get a Boolean: " + status.ToString()); 502 | throwException(env, err.c_str()); 503 | } 504 | } 505 | 506 | jbyteArray nativeGet(JNIEnv* env, jclass clazz, jstring jkey) { 507 | LOGI("Getting a ByteArray"); 508 | 509 | if (!isDBOpen) { 510 | throwException(env, "Database is not open"); 511 | } 512 | 513 | const char* key = env->GetStringUTFChars(jkey, 0); 514 | std::string data; 515 | leveldb::Status status = db->Get(leveldb::ReadOptions(), key, &data); 516 | 517 | env->ReleaseStringUTFChars(jkey, key); 518 | 519 | if (status.ok()) { 520 | int size = data.size(); 521 | char* elems = const_cast(data.data()); 522 | jbyteArray array = env->NewByteArray(size * sizeof(jbyte)); 523 | env->SetByteArrayRegion(array, 0, size, reinterpret_cast(elems)); 524 | return array; 525 | } else { 526 | std::string err("Failed to get a ByteArray: " + status.ToString()); 527 | throwException(env, err.c_str()); 528 | } 529 | } 530 | 531 | jboolean nativeExists(JNIEnv* env, jclass clazz, jstring jkey) { 532 | if (!isDBOpen) { 533 | throwException(env, "Database is not open"); 534 | } 535 | 536 | const char* key = env->GetStringUTFChars(jkey, 0); 537 | std::string value; 538 | leveldb::Status status = db->Get(leveldb::ReadOptions(), key, &value); 539 | 540 | env->ReleaseStringUTFChars(jkey, key); 541 | 542 | if (status.ok()) { 543 | return JNI_TRUE; 544 | } else if (status.IsNotFound()) { 545 | return JNI_FALSE; 546 | } else { 547 | std::string err("Failed to check if a key exists: " + status.ToString()); 548 | throwException(env, err.c_str()); 549 | } 550 | } 551 | 552 | static JNINativeMethod sMethods[] = { 553 | { "nativeOpen", "(Ljava/lang/String;)V", (void*) nativeOpen}, 554 | { "nativeClose", "()V", (void*) nativeClose}, 555 | { "nativeGet", "(Ljava/lang/String;)[B", (void*) nativeGet}, 556 | { "nativeGetString", "(Ljava/lang/String;)Ljava/lang/String;", (void*) nativeGetString}, 557 | { "nativeGetLong", "(Ljava/lang/String;)J", (void*) nativeGetLong}, 558 | { "nativeGetInt", "(Ljava/lang/String;)I", (void*) nativeGetInt}, 559 | { "nativeGetShort", "(Ljava/lang/String;)S", (void*) nativeGetShort}, 560 | { "nativeGetDouble", "(Ljava/lang/String;)D", (void*) nativeGetDouble}, 561 | { "nativeGetFloat", "(Ljava/lang/String;)F", (void*) nativeGetFloat}, 562 | { "nativeGetBoolean", "(Ljava/lang/String;)Z", (void*) nativeGetBoolean}, 563 | { "nativePut", "(Ljava/lang/String;[B)V", (void*) nativePut}, 564 | { "nativePutString", "(Ljava/lang/String;Ljava/lang/String;)V", (void*) nativePutString}, 565 | { "nativePutLong", "(Ljava/lang/String;J)V", (void*) nativePutLong}, 566 | { "nativePutInt", "(Ljava/lang/String;I)V", (void*) nativePutInt}, 567 | { "nativePutShort", "(Ljava/lang/String;S)V", (void*) nativePutShort}, 568 | { "nativePutDouble", "(Ljava/lang/String;D)V", (void*) nativePutDouble}, 569 | { "nativePutFloat", "(Ljava/lang/String;F)V", (void*) nativePutFloat}, 570 | { "nativePutBoolean", "(Ljava/lang/String;Z)V", (void*) nativePutBoolean}, 571 | { "nativeDelete", "(Ljava/lang/String;)V", (void*) nativeDelete }, 572 | { "nativeExists", "(Ljava/lang/String;)Z", (void*) nativeExists }, 573 | { "nativeDestroy", "(Ljava/lang/String;)V", (void*) nativeDestroy } 574 | }; 575 | 576 | int register_im_amomo_leveldb_LevelDB(JNIEnv *env) { 577 | jclass clazz = env->FindClass("im/amomo/leveldb/LevelDB"); 578 | if (!clazz) { 579 | LOGE("Can't find class im.amomo.leveldb.LevelDB"); 580 | return 0; 581 | } 582 | return env->RegisterNatives(clazz, sMethods, NELEM(sMethods)); 583 | } 584 | 585 | 586 | --------------------------------------------------------------------------------