├── .gitignore
├── .idea
└── codeStyleSettings.xml
├── .travis.yml
├── BENCHMARK.md
├── LICENSE
├── README.md
├── build.gradle
├── droidsnapper-sample-rx
├── build.gradle
├── proguard-rules.pro
└── src
│ └── main
│ ├── AndroidManifest.xml
│ ├── java
│ └── com
│ │ └── example
│ │ └── snapper
│ │ └── rx
│ │ ├── App.java
│ │ ├── MainActivity.java
│ │ ├── SnapperRxListAdapter.java
│ │ └── util
│ │ ├── RxSnapperListener.java
│ │ ├── SnapperChangeFilter.java
│ │ ├── SnapperChangeMapper.java
│ │ └── SnapperChangeSort.java
│ ├── project.properties
│ └── res
│ ├── layout
│ └── activity_main.xml
│ ├── mipmap-hdpi
│ └── ic_launcher.png
│ ├── mipmap-mdpi
│ └── ic_launcher.png
│ ├── mipmap-xhdpi
│ └── ic_launcher.png
│ ├── mipmap-xxhdpi
│ └── ic_launcher.png
│ ├── values-w820dp
│ └── dimens.xml
│ └── values
│ ├── dimens.xml
│ ├── strings.xml
│ └── styles.xml
├── droidsnapper-sample
├── build.gradle
├── proguard-rules.pro
└── src
│ └── main
│ ├── AndroidManifest.xml
│ ├── java
│ └── com
│ │ └── example
│ │ └── snapper
│ │ ├── App.java
│ │ ├── MainActivity.java
│ │ └── ProjectionArrayAdapter.java
│ ├── project.properties
│ └── res
│ ├── layout
│ ├── activity_main.xml
│ └── user_cell.xml
│ ├── mipmap-hdpi
│ └── ic_launcher.png
│ ├── mipmap-mdpi
│ └── ic_launcher.png
│ ├── mipmap-xhdpi
│ └── ic_launcher.png
│ ├── mipmap-xxhdpi
│ └── ic_launcher.png
│ ├── values-w820dp
│ └── dimens.xml
│ └── values
│ ├── dimens.xml
│ ├── strings.xml
│ └── styles.xml
├── droidsnapper
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── io
│ │ └── techery
│ │ └── snapper
│ │ ├── BaseAsyncTestCase.java
│ │ ├── BaseSyncTestCase.java
│ │ ├── BaseTestCase.java
│ │ ├── model
│ │ ├── Company.java
│ │ └── User.java
│ │ ├── test
│ │ ├── BasicOperationsTest.java
│ │ ├── HelpersTest.java
│ │ ├── ManyCollectionsTest.java
│ │ └── benchmark
│ │ │ ├── PerformanceTest.java
│ │ │ └── ProjectionPerformanceTest.java
│ │ └── util
│ │ └── ModelUtil.java
│ └── main
│ ├── AndroidManifest.xml
│ └── java
│ └── io
│ └── techery
│ └── snapper
│ └── droidsnapper
│ ├── DroidSnapper.java
│ └── helper
│ └── MainThreadDataListener.java
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── settings.gradle
├── snapper-converters
└── kryo
│ ├── build.gradle
│ └── src
│ └── main
│ └── java
│ └── io
│ └── techery
│ └── snapper
│ └── kryo
│ ├── KryoConverter.java
│ └── KryoConverterFactory.java
├── snapper-persisters
└── snappydb
│ ├── build.gradle
│ └── src
│ └── main
│ ├── AndroidManifest.xml
│ └── java
│ └── io
│ └── techery
│ └── snapper
│ └── snappydb
│ ├── SnappyStorageFactory.java
│ ├── SnappyStoragePersister.java
│ ├── SnappyStoragePersisterFactory.java
│ └── SnappySweeper.java
└── snapper
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
└── main
└── java
└── io
└── techery
└── snapper
├── Snapper.java
├── converter
├── ObjectConverter.java
└── ObjectConverterFactory.java
├── datacollection
├── DataCollection.java
├── DataCollectionFactory.java
├── DefaultDataCollectionFactory.java
└── naming
│ ├── DataCollectionNamingFactory.java
│ └── DefaultDataCollectionNamingFactory.java
├── dataset
├── DataSet.java
├── DataSetJoin.java
├── DataSetMap.java
└── IDataSet.java
├── executor
├── ExecutorFactory.java
├── FixedExecutorFactory.java
├── SimpleExecutorService.java
└── SnapperThreadFactory.java
├── helper
└── SingleItemDataListener.java
├── model
├── Indexable.java
└── ItemRef.java
├── projection
├── IProjection.java
├── Projection.java
└── ProjectionBuilder.java
├── storage
├── CachingStorage.java
├── Storage.java
├── StorageChange.java
├── StorageFactory.java
├── StoragePersister.java
└── StoragePersisterFactory.java
├── sweeper
└── Sweeper.java
└── util
└── ListUtils.java
/.gitignore:
--------------------------------------------------------------------------------
1 | # svn
2 | *.svn*
3 |
4 | # built application files
5 | *.apk
6 | *.ap_
7 |
8 | # files for the dex VM
9 | *.dex
10 |
11 | # Java class files
12 | *.class
13 |
14 | # generated GUI files
15 | */R.java
16 |
17 | # generated folder
18 | bin
19 | gen
20 |
21 | # local
22 | local.properties
23 | proguard.cfg
24 |
25 | # log files
26 | log*.txt
27 |
28 | # archives
29 | *.gz
30 | *.tar
31 | *.zip
32 |
33 | # eclipse
34 | *.metadata
35 | *.settings
36 |
37 | # Android Studio
38 | .idea/*
39 | **/*/.idea
40 | !.idea/codeStyleSettings.xml
41 | .gradle
42 | */local.properties
43 | */out
44 | build
45 | *.iml
46 | *.iws
47 | *.ipr
48 | *~
49 | *.swp
50 |
51 | .DS_Store
--------------------------------------------------------------------------------
/.idea/codeStyleSettings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
227 |
228 |
229 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: android
2 | jdk: oraclejdk8
3 |
4 | ### Dependencies
5 |
6 | env:
7 | global:
8 | - ANDROID_TARGET=android-23
9 | - ANDROID_EMULATOR_TARGET=android-21
10 | - ANDROID_ABI=armeabi-v7a
11 | - ANDROID_BUILD_TOOLS=23.0.3
12 | - ADB_INSTALL_TIMEOUT=8 # avoid timeout exception
13 |
14 | android:
15 | components:
16 | - tools
17 | - platform-tools
18 | - build-tools-$ANDROID_BUILD_TOOLS
19 | - $ANDROID_TARGET
20 | - ANDROID_EMULATOR_TARGET
21 | - sys-img-$ANDROID_ABI-$ANDROID_EMULATOR_TARGET
22 | - extra-android-support
23 | - extra-android-m2repository
24 | licenses:
25 | - 'android-sdk-license-.+'
26 |
27 | ### Misc. configurations
28 |
29 | sudo: false
30 | before_cache:
31 | - rm -f $HOME/.gradle/caches/modules-2/modules-2.lock
32 | cache:
33 | directories:
34 | - $HOME/.m2
35 | - $HOME/.gradle/caches/
36 | - $HOME/.gradle/wrapper/
37 |
38 | ### Emulator preparations
39 |
40 | before_script:
41 | - echo no | android create avd --force -n test -t $ANDROID_EMULATOR_TARGET --abi $ANDROID_ABI
42 | - emulator -avd test -no-skin -no-audio -no-window -memory 256 &
43 | - android-wait-for-emulator
44 | - adb shell input keyevent 82 &
45 |
46 | ### The Job
47 |
48 | script:
49 | - ./gradlew --info clean droidsnapper:connectedAndroidTest droidsnapper:assembleDebug droidsnapper-sample:assembleDebug droidsnapper-sample-rx:assembleDebug -PdisablePreDex
--------------------------------------------------------------------------------
/BENCHMARK.md:
--------------------------------------------------------------------------------
1 | ## Benchmark
2 | Insert/Load/Clear 25000 items on Emulator, Genymotion and Nexus 7 (2013).
3 | Benchmark tests are located at `io.techery.snapper.test.benchmark` package.
4 |
5 | ### Emulator
6 |
7 | + Insert
8 | ```
9 | | 0.000 ms | Batch Insert
10 | | 3216.919 ms | Storage update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0}
11 | | 57.606 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0}
12 | | 46.974 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0}
13 | | 65.759 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0}
14 | | 59.351 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0}
15 | | 38.515 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0}
16 | | 2.051 ms | END of Batch Insert
17 | |
18 | final: 3487.175 ms
19 | ```
20 |
21 | + Load
22 | ```
23 | | 0.000 ms | Batch Load
24 | | 2396.487 ms | Storage update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0}
25 | | 42.216 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0}
26 | | 23.289 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0}
27 | | 37.384 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0}
28 | | 51.291 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0}
29 | | 50.593 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0}
30 | | 2.112 ms | END of Batch Load
31 | |
32 | final: 2603.371 ms
33 | ```
34 |
35 | + Clear
36 | ```
37 | | 0.000 ms | Batch Clear
38 | | 926.022 ms | Storage update, items count is 0 change is StorageChange{added=0, updated=0, removed=25000}
39 | | 4601.738 ms | Projection update, items count is 0 change is StorageChange{added=0, updated=0, removed=25000}
40 | | 3726.414 ms | Projection update, items count is 0 change is StorageChange{added=0, updated=0, removed=25000}
41 | | 3499.932 ms | Projection update, items count is 0 change is StorageChange{added=0, updated=0, removed=25000}
42 | | 3464.880 ms | Projection update, items count is 0 change is StorageChange{added=0, updated=0, removed=25000}
43 | | 3698.451 ms | Projection update, items count is 0 change is StorageChange{added=0, updated=0, removed=25000}
44 | | 1.578 ms | END of Batch Clear
45 | |
46 | final: 19919.015 ms
47 | ```
48 |
49 | ### Genymotion
50 |
51 | + Insert
52 | ```
53 | | 0.000 ms | Batch Insert
54 | | 2707.703 ms | Storage update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0}
55 | | 217.081 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0}
56 | | 123.055 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0}
57 | | 116.949 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0}
58 | | 107.740 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0}
59 | | 150.817 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0}
60 | | 0.035 ms | END of Batch Insert
61 | |
62 | final: 3423.381 ms
63 | ```
64 |
65 | + Load
66 | ```
67 | | 0.000 ms | Batch Load
68 | | 2287.892 ms | Storage update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0}
69 | | 126.722 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0}
70 | | 147.331 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0}
71 | | 144.558 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0}
72 | | 118.805 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0}
73 | | 143.937 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0}
74 | | 0.033 ms | END of Batch Load
75 | |
76 | final: 2969.278 ms
77 | ```
78 |
79 | + Clear
80 | ```
81 | | 0.000 ms | Batch Clear
82 | | 771.553 ms | Storage update, items count is 0 change is StorageChange{added=0, updated=0, removed=25000}
83 | | 22550.293 ms | Projection update, items count is 0 change is StorageChange{added=0, updated=0, removed=25000}
84 | | 22153.366 ms | Projection update, items count is 0 change is StorageChange{added=0, updated=0, removed=25000}
85 | | 21780.841 ms | Projection update, items count is 0 change is StorageChange{added=0, updated=0, removed=25000}
86 | | 20937.838 ms | Projection update, items count is 0 change is StorageChange{added=0, updated=0, removed=25000}
87 | | 20756.431 ms | Projection update, items count is 0 change is StorageChange{added=0, updated=0, removed=25000}
88 | | 0.034 ms | END of Batch Clear
89 | |
90 | final: 108950.357 ms
91 | ```
92 |
93 | ### Nexus 7 (2013)
94 |
95 | + Insert
96 | ```
97 | | 0.000 ms | Batch Insert
98 | | 7083.557 ms | Storage update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0}
99 | | 354.095 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0}
100 | | 272.369 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0}
101 | | 361.389 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0}
102 | | 179.077 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0}
103 | | 292.511 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0}
104 | | 0.092 ms | END of Batch Insert
105 | |
106 | final: 8543.091 ms
107 | ```
108 |
109 | + Load
110 | ```
111 | | 0.000 ms | Batch Load
112 | | 7984.528 ms | Storage update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0}
113 | | 337.952 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0}
114 | | 296.509 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0}
115 | | 309.448 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0}
116 | | 320.160 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0}
117 | | 328.094 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0}
118 | | 0.305 ms | END of Batch Load
119 | |
120 | final: 9576.996 ms
121 | ```
122 |
123 | + Clear
124 | ```
125 | | 0.000 ms | Batch Clear
126 | | 2934.570 ms | Storage update, items count is 0 change is StorageChange{added=0, updated=0, removed=25000}
127 | | 38443.512 ms | Projection update, items count is 0 change is StorageChange{added=0, updated=0, removed=25000}
128 | | 38543.610 ms | Projection update, items count is 0 change is StorageChange{added=0, updated=0, removed=25000}
129 | | 37971.191 ms | Projection update, items count is 0 change is StorageChange{added=0, updated=0, removed=25000}
130 | | 38011.871 ms | Projection update, items count is 0 change is StorageChange{added=0, updated=0, removed=25000}
131 | | 38447.601 ms | Projection update, items count is 0 change is StorageChange{added=0, updated=0, removed=25000}
132 | | 0.092 ms | END of Batch Clear
133 | |
134 | final: 194352.448 ms
135 | ```
136 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
203 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ## Snapper
2 | NoSQL fast-serializable storage with Projections, Sorting, Filtering and more.
3 |
4 | ## Overview
5 | NoSQL db is great in simplicity.
6 | `Snapper` is simple but yet functional:
7 | it's based on idea that every `POJO` could be addressed as typed `DataCollection` with
8 | any kind of `Projection` (aka sub-set) for filtering, sorting, mapping or joining.
9 | Such `DataCollection`\\`Projection` is observable and reacts to changes from parent `DataSet`.
10 |
11 | ## Performance
12 | Timing is very close to fastest `SQLite`-based DBs.
13 | See [Benchmark test results](BENCHMARK.md) for details.
14 |
15 | ## Getting started
16 | ### Core objects
17 | `DroidSnapper` is main controller for `DataCollection`(s) - data provider objects.
18 | It's thread safe Singleton:
19 |
20 | ```java
21 | DataCollection userCollection = DroidSnapper.with(context).collection(User.class);
22 | ```
23 | `DataCollection` itself is used for:
24 | - data manipulation
25 |
26 | ```java
27 | userCollection.insert(new User(1, "Jim")); // add user with id=1
28 | userCollection.insert(new User(1, "Jim Defoe")); // replace user by id
29 | ```
30 | _Note_: all data-related work is done on background `Executor` so `MainThread`-friendly.
31 | - data observation
32 |
33 | ```java
34 | userCollection.addDataListener(new IDataSet.DataListener() {
35 | @Override
36 | public void onDataUpdated(List items, StorageChange change) {
37 | //
38 | }
39 | });
40 | ```
41 | _Note_: `DataCollection` holds memory cache from it's storage for better performance;
42 |
43 | _Note_: listener is called right away upon addition. It's guaranteed that `DataCollection` is in costistent state (read initialized) when callback is called.
44 |
45 | _Caution_: listener is called from `Executor`'s thread,
46 | it's up to `DataListener` to proxy calls to another thread, e.g. [MainThreadDataListener](droidsnapper/src/main/java/io/techery/snapper/droidsnapper/helper/MainThreadDataListener.java).
47 | - `Projection` creation:
48 |
49 | ```java
50 | Projection jimProjection = userCollection.projection()
51 | .where(new Predicate() {
52 | @Override
53 | public boolean apply(User element) {
54 | return element.name.contains("Jim");
55 | }
56 | }).build();
57 | jimProjection.addDataListener(...);
58 | ```
59 | `Projection` is a subset of parent `DataSet` which `DataCollection` or another `Projection` is.
60 | It's used for:
61 | - sub-projection with conditional filtering/sorting;
62 | - data observation.
63 |
64 | ### Data Model
65 | Every model must implement `Indexable` interface, e.g.:
66 | ```java
67 | public class User implements Indexable {
68 |
69 | public final int id;
70 |
71 | public User(int id) {
72 | this.id = id;
73 | }
74 |
75 | @Override
76 | public byte[] index() {
77 | return ByteBuffer.allocate(4).putInt(id).array();
78 | }
79 | }
80 | ```
81 | - `index()` is used as unique key for each object;
82 | - insertion will replace (update) object with same index.
83 |
84 | ## Advanced usage
85 | ### DataCollection naming
86 | Every POJO storage is named with POJO's `class#getSimpleName()`, but could be labeled for uniqueness:
87 | ```java
88 | DataCollection userCollection = DroidSnapper.with(context).collection(User.class);
89 | DataCollection friendsCollection = DroidSnapper.with(context).collection(User.class, "friends");
90 | ```
91 | ### Advanced DataSet(s)
92 | #### Joining
93 | Connects two `DataSet`s to listen for their changes:
94 | ```java
95 | DataSetJoin> companyUserJoin =
96 | new JoinBuilder<>(companyStorage, userStorage)
97 | .setJoinFunction(new Function2() {
98 | @Override public Boolean apply(Company company, User user) {
99 | return company.getId() == user.getCompanyId();
100 | }
101 | })
102 | .setMapFunction(new Function2, Pair>() {
103 | @Override public Pair apply(Company company, List users) {
104 | User user = users.isEmpty() ? null : users.get(0);
105 | return new Pair<>(company, user);
106 | }
107 | }).create();
108 | ```
109 | #### Mapping
110 | Creates virtual relation between `DataSet` objects and some type:
111 | ```java
112 | DataSetMap userIdMap = new DataSetMap(dataCollection, new Function1() {
113 | @Override
114 | public Integer apply(User user) {
115 | return user.id;
116 | }
117 | });
118 | userIdMap.addDataListener(new IDataSet.DataListener() {
119 | @Override
120 | public void onDataUpdated(List items, StorageChange change) {
121 | //
122 | }
123 | });
124 | ```
125 | #### Rx support
126 | `DataListener` is wrappable with Rx goodies, see [Rx Sample](droidsnapper-sample-rx/src/main/java/com/example/snapper/rx) for details.
127 |
128 | ### Resources Cleanup
129 | - Every collection could be closed with `DataCollection#close()`
130 | - All collections are closed via `Snapper#close()`
131 |
132 | ## Under the hood
133 | `DroidSnapper` is a `Snapper` instance with default impl. of `Snapper`'s components, those are:
134 | - `DataCollectionNamingFactory` - creates names for collections depending on it's model's class and custom label;
135 | - `DataCollectionFactory` creates a `DataCollection` per POJO's model, every collection involves;
136 | - `StorageFactory` provides storage to put/get collection's items;
137 | - `ExecutorFactory` provides `ExecutorService` to perform collection actions;
138 |
139 | `Storage` impl. could differ and up to developer.
140 | Anyway `Snapper` provides `CachingStorage` with in-mem cache and forwarding calls to it's disk persister.
141 | `CachingStorage` uses `ObjectConverter` to convert POJO to bytes and vice versa.
142 |
143 | It means one can easily create own no-sql storage with own components of choice.
144 |
145 | `DroidSnapper` uses
146 | - `CachingStorage` to hold collection's items in memory for best performance;
147 | - [SnappyDB](https://github.com/nhachicha/SnappyDB) as `StoragePersister`
148 | - [Kryo](https://github.com/EsotericSoftware/kryo) as `ObjectConverter`
149 |
150 | ## Dev. status
151 | Tested in production.
152 |
153 | [](https://travis-ci.org/techery/snapper)
154 | 
155 |
156 | ## Installation
157 | ```groovy
158 | repositories {
159 | maven { url "https://jitpack.io" }
160 | }
161 | dependencies {
162 | compile 'com.github.techery.snapper:droidsnapper:{latestVersion}'
163 | }
164 | ```
165 |
166 | ## License
167 |
168 | Copyright (c) 2015 Techery
169 |
170 | Licensed under the Apache License, Version 2.0 (the "License");
171 | you may not use this file except in compliance with the License.
172 | You may obtain a copy of the License at
173 |
174 | http://www.apache.org/licenses/LICENSE-2.0
175 |
176 | Unless required by applicable law or agreed to in writing, software
177 | distributed under the License is distributed on an "AS IS" BASIS,
178 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
179 | See the License for the specific language governing permissions and
180 | limitations under the License.
181 |
182 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 | buildscript {
3 | repositories {
4 | jcenter()
5 | }
6 | dependencies {
7 | classpath 'com.android.tools.build:gradle:2.0.0'
8 | classpath 'com.github.dcendents:android-maven-gradle-plugin:1.3'
9 | classpath 'com.github.ben-manes:gradle-versions-plugin:0.12.0'
10 | }
11 | }
12 |
13 | ext {
14 | compileSdkVersion = 23
15 | buildToolsVersion = '23.0.3'
16 | minSdkVersion = 15
17 | targetSdkVersion = 22
18 | }
19 |
20 | ///////////////////////////////////
21 | // Misc dependencies and properties
22 | ///////////////////////////////////
23 |
24 | // System properties
25 | ext.preDexLibs = !project.hasProperty('disablePreDex')
--------------------------------------------------------------------------------
/droidsnapper-sample-rx/build.gradle:
--------------------------------------------------------------------------------
1 | buildscript {
2 | repositories {
3 | jcenter()
4 | }
5 | dependencies {
6 | classpath 'com.android.tools.build:gradle:2.0.0'
7 | classpath 'me.tatarka:gradle-retrolambda:3.2.5'
8 | classpath 'com.github.ben-manes:gradle-versions-plugin:0.12.0'
9 | }
10 | }
11 |
12 | apply plugin: 'com.android.application'
13 | apply plugin: 'me.tatarka.retrolambda'
14 | apply plugin: 'com.github.ben-manes.versions'
15 |
16 | android {
17 | compileSdkVersion rootProject.ext.compileSdkVersion
18 | buildToolsVersion rootProject.ext.buildToolsVersion
19 |
20 | defaultConfig {
21 | applicationId "com.example.droidsnapper.rx"
22 | minSdkVersion rootProject.ext.minSdkVersion
23 | targetSdkVersion rootProject.ext.targetSdkVersion
24 | }
25 |
26 | buildTypes {
27 | release {
28 | minifyEnabled false
29 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
30 | }
31 | }
32 |
33 | compileOptions {
34 | sourceCompatibility JavaVersion.VERSION_1_8
35 | targetCompatibility JavaVersion.VERSION_1_8
36 | }
37 | }
38 |
39 | repositories {
40 | jcenter()
41 | maven { url "https://jitpack.io" }
42 | }
43 |
44 | dependencies {
45 | compile project(':droidsnapper')
46 | //
47 | compile 'io.reactivex:rxjava:1.1.3'
48 | compile 'io.reactivex:rxandroid:1.1.0'
49 | compile 'com.trello:rxlifecycle:0.5.0'
50 | compile 'com.trello:rxlifecycle-components:0.5.0'
51 | compile 'com.jakewharton.rxbinding:rxbinding:0.4.0'
52 | //
53 | compile 'com.github.techery:RxListAdapter:0.1.1'
54 | //
55 | compile 'com.android.support:appcompat-v7:23.3.0'
56 | //
57 | compile 'com.jakewharton:butterknife:7.0.1'
58 | compile 'com.jakewharton.timber:timber:4.1.2'
59 | }
60 |
--------------------------------------------------------------------------------
/droidsnapper-sample-rx/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Users/zen/Library/Android/sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
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 | #}
18 |
--------------------------------------------------------------------------------
/droidsnapper-sample-rx/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
13 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/droidsnapper-sample-rx/src/main/java/com/example/snapper/rx/App.java:
--------------------------------------------------------------------------------
1 | package com.example.snapper.rx;
2 |
3 | import android.app.Application;
4 | import android.content.Context;
5 |
6 | import timber.log.Timber;
7 | import timber.log.Timber.DebugTree;
8 |
9 | public class App extends Application {
10 |
11 | @Override
12 | public void onCreate() {
13 | super.onCreate();
14 | instance = this;
15 |
16 | if (BuildConfig.DEBUG) {
17 | Timber.plant(new DebugTree());
18 | } else {
19 | // TODO Crashlytics.start(this);
20 | // TODO Timber.plant(new CrashlyticsTree());
21 | }
22 |
23 | }
24 |
25 | ///////////////////////////////////////////////////////////////////////////
26 | // Static helper
27 | ///////////////////////////////////////////////////////////////////////////
28 |
29 | public static App from(Context context) {
30 | return (App) context.getApplicationContext();
31 | }
32 |
33 | private static App instance;
34 |
35 | public static App instance() {
36 | return instance;
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/droidsnapper-sample-rx/src/main/java/com/example/snapper/rx/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.example.snapper.rx;
2 |
3 | import android.content.Context;
4 | import android.os.Bundle;
5 | import android.support.v7.app.AppCompatActivity;
6 | import android.support.v7.widget.LinearLayoutManager;
7 | import android.support.v7.widget.RecyclerView;
8 | import android.util.Pair;
9 | import android.view.LayoutInflater;
10 | import android.view.View;
11 | import android.view.ViewGroup;
12 | import android.widget.TextView;
13 |
14 | import com.example.snapper.rx.util.RxSnapperListener;
15 | import com.example.snapper.rx.util.SnapperChangeFilter;
16 | import com.example.snapper.rx.util.SnapperChangeSort;
17 |
18 | import java.nio.ByteBuffer;
19 | import java.util.ArrayList;
20 | import java.util.List;
21 |
22 | import butterknife.Bind;
23 | import butterknife.ButterKnife;
24 | import butterknife.OnClick;
25 | import io.techery.snapper.datacollection.DataCollection;
26 | import io.techery.snapper.droidsnapper.DroidSnapper;
27 | import io.techery.snapper.model.Indexable;
28 | import io.techery.snapper.projection.IProjection;
29 | import io.techery.snapper.storage.StorageChange;
30 | import rx.Observable;
31 | import rx.subjects.ReplaySubject;
32 |
33 |
34 | public class MainActivity extends AppCompatActivity {
35 |
36 | DataCollection dataCollection;
37 | IProjection projection;
38 | //
39 | ReplaySubject filteringSignal = ReplaySubject.createWithSize(1);
40 | volatile int lastId;
41 | //
42 | static final int BATCH_PUT_COUNT = 10000;
43 |
44 | @Bind(R.id.listView)
45 | RecyclerView recyclerView;
46 | UserAdapter usersAdapter;
47 |
48 | @Override
49 | protected void onCreate(Bundle savedInstanceState) {
50 | super.onCreate(savedInstanceState);
51 | setContentView(R.layout.activity_main);
52 | ButterKnife.bind(this);
53 |
54 | dataCollection = DroidSnapper.with(this).collection(User.class);
55 | projection = dataCollection.projection().build();
56 | //
57 | RxSnapperListener snapperListener = new RxSnapperListener<>();
58 | projection.addDataListener(snapperListener);
59 |
60 | boolean filter;
61 | if (savedInstanceState == null) filter = false;
62 | else filter = savedInstanceState.getBoolean("filter");
63 | filteringSignal.onNext(filter);
64 |
65 | Observable, StorageChange>> source =
66 | filteringSignal.asObservable()
67 | .flatMap(filterOn -> snapperListener.observable()
68 | .compose(new SnapperChangeSort<>((u1, u2) -> {
69 | if (u1.id < u2.id) return 1;
70 | else if (u1.id > u2.id) return -1;
71 | else return 0;
72 | }))
73 | .doOnNext(pair -> {
74 | List items = pair.first;
75 | if (items.isEmpty()) lastId = 0;
76 | else lastId = items.get(0).id;
77 | })
78 | .compose(new SnapperChangeFilter<>(user -> {
79 | if (!filterOn) return true;
80 | else return user.id % 10 == 0;
81 | }))
82 | );
83 | usersAdapter = new UserAdapter(this, source);
84 | recyclerView.setAdapter(usersAdapter);
85 | recyclerView.setLayoutManager(new LinearLayoutManager(this));
86 | }
87 |
88 | @Override
89 | public void onSaveInstanceState(Bundle outState) {
90 | super.onSaveInstanceState(outState);
91 | outState.putBoolean("filter", filteringSignal.getValue());
92 | }
93 |
94 | @Override
95 | protected void onDestroy() {
96 | projection.close();
97 | super.onDestroy();
98 | }
99 |
100 | @OnClick(R.id.add)
101 | void onAddClick() {
102 | dataCollection.insert(genUser(lastId + 1));
103 | }
104 |
105 | @OnClick(R.id.add_many)
106 | void onAddManyClick() {
107 | List users = new ArrayList<>();
108 | int lastId = this.lastId + 1;
109 | for (int i = 0; i < BATCH_PUT_COUNT; i++) {
110 | users.add(genUser(lastId + i));
111 | }
112 | dataCollection.insertAll(users);
113 | }
114 |
115 | @OnClick(R.id.filter)
116 | void onFilterClick() {
117 | filteringSignal.onNext(!filteringSignal.getValue());
118 | }
119 |
120 | @OnClick(R.id.clear)
121 | void onClearClick() {
122 | dataCollection.clear();
123 | }
124 |
125 | ///////////////////////////////////////////////////////////////////////////
126 | // Adapter
127 | ///////////////////////////////////////////////////////////////////////////
128 |
129 | static class UserAdapter extends SnapperRxListAdapter {
130 |
131 | public UserAdapter(Context context, Observable, StorageChange>> source) {
132 | super(context, source);
133 | }
134 |
135 | @Override
136 | public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
137 | LayoutInflater inflater = LayoutInflater.from(context);
138 | View itemView = inflater.inflate(android.R.layout.simple_list_item_1, parent, false);
139 | return new ViewHolder(itemView);
140 | }
141 |
142 | @Override
143 | public void onBindViewHolder(ViewHolder holder, int position) {
144 | User user = getItem(position);
145 | ((TextView) holder.itemView).setText(String.valueOf(user.getId()));
146 | }
147 |
148 | static class ViewHolder extends RecyclerView.ViewHolder {
149 |
150 | public ViewHolder(View itemView) {
151 | super(itemView);
152 | }
153 | }
154 | }
155 |
156 |
157 | ///////////////////////////////////////////////////////////////////////////
158 | // User model
159 | ///////////////////////////////////////////////////////////////////////////
160 |
161 | static User genUser(int i) {
162 | User u = new User(i);
163 | u.email = String.valueOf(Math.random() * 100);
164 | u.name = String.valueOf(Math.random() * 100);
165 | u.price = (float) Math.random();
166 | u.isActive = Math.random() % 2 == 0;
167 | return u;
168 | }
169 |
170 | public static class User implements Indexable {
171 | public int id;
172 | public String name;
173 | public float price;
174 | public String email;
175 |
176 | public boolean isActive;
177 |
178 | public User() {
179 | }
180 |
181 | public User(int id) {
182 | this.id = id;
183 | }
184 |
185 | @Override
186 | public byte[] index() {
187 | return ByteBuffer.allocate(4).putInt(id).array();
188 | }
189 |
190 | @Override
191 | public boolean equals(Object o) {
192 | if (this == o) return true;
193 | if (o == null || getClass() != o.getClass()) return false;
194 |
195 | User user = (User) o;
196 |
197 | return id == user.id;
198 |
199 | }
200 |
201 | @Override
202 | public int hashCode() {
203 | return id;
204 | }
205 |
206 | public int getId() {
207 | return id;
208 | }
209 |
210 | public void setId(int id) {
211 | this.id = id;
212 | }
213 |
214 | public String getName() {
215 | return name;
216 | }
217 |
218 | public void setName(String name) {
219 | this.name = name;
220 | }
221 |
222 | public float getPrice() {
223 | return price;
224 | }
225 |
226 | public void setPrice(float price) {
227 | this.price = price;
228 | }
229 |
230 | public String getEmail() {
231 | return email;
232 | }
233 |
234 | public void setEmail(String email) {
235 | this.email = email;
236 | }
237 |
238 | public boolean isActive() {
239 | return isActive;
240 | }
241 |
242 | public void setIsActive(boolean isActive) {
243 | this.isActive = isActive;
244 | }
245 |
246 | @Override
247 | public String toString() {
248 | return "User{" +
249 | "id=" + id +
250 | '}';
251 | }
252 |
253 | }
254 | }
255 |
--------------------------------------------------------------------------------
/droidsnapper-sample-rx/src/main/java/com/example/snapper/rx/SnapperRxListAdapter.java:
--------------------------------------------------------------------------------
1 | package com.example.snapper.rx;
2 |
3 | import android.content.Context;
4 | import android.support.v7.widget.RecyclerView;
5 | import android.util.Pair;
6 |
7 | import java.util.ArrayList;
8 | import java.util.List;
9 |
10 | import io.techery.rxlistadapter.RxAdapterBridge;
11 | import io.techery.rxlistadapter.RxListAdapter;
12 | import io.techery.snapper.model.ItemRef;
13 | import io.techery.snapper.storage.StorageChange;
14 | import rx.Observable;
15 | import rx.Subscriber;
16 |
17 | public abstract class SnapperRxListAdapter extends RxListAdapter, StorageChange>, VH> {
18 |
19 | public SnapperRxListAdapter(Context context, Observable, StorageChange>> source) {
20 | super(context, new ArrayList<>(), source);
21 | }
22 |
23 | @Override
24 | public RxAdapterBridge, StorageChange>> createRxAdapterBridge(List items, Observable, StorageChange>> source) {
25 | return new RxChangeAdapterBridge(this, source, items);
26 | }
27 |
28 | private static class RxChangeAdapterBridge extends RxAdapterBridge, StorageChange>> {
29 |
30 | public RxChangeAdapterBridge(RecyclerView.Adapter adapter, Observable, StorageChange>> source, List items) {
31 | super(adapter, source, items);
32 | }
33 |
34 | @Override protected Subscriber, StorageChange>> subscriber() {
35 | return new Subscriber, StorageChange>>() {
36 | @Override public void onNext(Pair, StorageChange> ts) {
37 | List newItems = ts.first;
38 | StorageChange storageChange = ts.second;
39 | if (itemsEquals(newItems, storageChange)) return;
40 | //
41 | if (items.isEmpty()) {
42 | setNewItems(newItems);
43 | } else {
44 | for (ItemRef item : storageChange.getAdded()) {
45 | onAdded(newItems, item.getValue());
46 | }
47 | for (ItemRef item : storageChange.getRemoved()) {
48 | onRemoved(item.getValue());
49 | }
50 | for (ItemRef item : storageChange.getUpdated()) {
51 | onUpdated(newItems, item.getValue());
52 | }
53 | }
54 | if (items.size() != newItems.size()) setNewItems(newItems);
55 | }
56 |
57 | private boolean itemsEquals(List newItems, StorageChange storageChange) {
58 | return items.equals(newItems) && storageChange.getUpdated().size() == 0;
59 | }
60 |
61 | private void setNewItems(List newItems) {
62 | items.clear();
63 | items.addAll(newItems);
64 | adapter.notifyDataSetChanged();
65 | }
66 |
67 | private void onAdded(List newItems, T value) {
68 | if (items.contains(value)) return;
69 | int i = newItems.indexOf(value);
70 | items.add(i, value);
71 | adapter.notifyItemInserted(i);
72 | }
73 |
74 | private void onRemoved(T item) {
75 | int pos = items.indexOf(item);
76 | if (pos == -1) return;
77 | items.remove(item);
78 | adapter.notifyItemRemoved(pos);
79 | }
80 |
81 | private void onUpdated(List newItems, T item) {
82 | int oldPos = items.indexOf(item);
83 | if (oldPos == -1) return;
84 | int newPos = newItems.indexOf(item);
85 | if (oldPos == newPos) {
86 | items.set(oldPos, item);
87 | adapter.notifyItemChanged(oldPos);
88 | } else {
89 | items.remove(oldPos);
90 | if (newPos > items.size()) newPos = items.size();
91 | items.add(newPos, item);
92 | adapter.notifyItemMoved(oldPos, newPos);
93 | }
94 | }
95 |
96 | @Override public void onCompleted() {
97 | }
98 |
99 | @Override public void onError(Throwable e) {
100 | }
101 | };
102 | }
103 | }
104 | }
105 |
--------------------------------------------------------------------------------
/droidsnapper-sample-rx/src/main/java/com/example/snapper/rx/util/RxSnapperListener.java:
--------------------------------------------------------------------------------
1 | package com.example.snapper.rx.util;
2 |
3 | import android.util.Pair;
4 |
5 | import java.util.List;
6 |
7 | import io.techery.snapper.dataset.IDataSet;
8 | import io.techery.snapper.storage.StorageChange;
9 | import rx.Observable;
10 | import rx.functions.Func1;
11 | import rx.subjects.ReplaySubject;
12 |
13 | public class RxSnapperListener implements IDataSet.DataListener, IDataSet.StatusListener {
14 |
15 | private final ReplaySubject, StorageChange>> subject;
16 | private final String tag;
17 |
18 | public RxSnapperListener() {
19 | this(null);
20 | }
21 |
22 | public RxSnapperListener(String tag) {
23 | this.subject = ReplaySubject.createWithSize(1);
24 | this.tag = tag;
25 | }
26 |
27 | @Override public void onDataUpdated(List list, StorageChange storageChange) {
28 | subject.onNext(new Pair<>(list, storageChange));
29 | }
30 |
31 | @Override public void onClosed() {
32 | subject.onCompleted();
33 | }
34 |
35 | ///////////////////////////////////////////////////////////////////////////
36 | // Public
37 | ///////////////////////////////////////////////////////////////////////////
38 |
39 | public Observable, StorageChange>> observable() {
40 | return subject.asObservable();
41 | }
42 |
43 | public Observable> listObservable() {
44 | return subject.map(new Func1, StorageChange>, List>() {
45 | @Override public List call(Pair, StorageChange> pair) {
46 | return pair.first;
47 | }
48 | });
49 | }
50 |
51 | public Observable> changeObservable() {
52 | return subject.map(new Func1, StorageChange>, StorageChange>() {
53 | @Override public StorageChange call(Pair, StorageChange> pair) {
54 | return pair.second;
55 | }
56 | });
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/droidsnapper-sample-rx/src/main/java/com/example/snapper/rx/util/SnapperChangeFilter.java:
--------------------------------------------------------------------------------
1 | package com.example.snapper.rx.util;
2 |
3 | import android.util.Pair;
4 |
5 | import java.util.List;
6 |
7 | import io.techery.snapper.model.Indexable;
8 | import io.techery.snapper.model.ItemRef;
9 | import io.techery.snapper.storage.StorageChange;
10 | import rx.Observable;
11 | import rx.Observable.Transformer;
12 | import rx.functions.Func1;
13 |
14 | public class SnapperChangeFilter implements Transformer, StorageChange>, Pair, StorageChange>> {
15 |
16 | private final Func1, StorageChange>, Pair, StorageChange>> filter;
17 |
18 | public SnapperChangeFilter(Func1 predicate) {
19 | this.filter = createFilter(predicate);
20 | }
21 |
22 | @Override
23 | public Observable, StorageChange>> call(Observable, StorageChange>> source) {
24 | return source.map(this.filter::call);
25 |
26 | }
27 |
28 | private Func1, StorageChange>, Pair, StorageChange>> createFilter(Func1 predicate) {
29 | return pair -> {
30 | List result = Observable.from(pair.first).filter(predicate).toList().toBlocking().first();
31 | StorageChange storageChange;
32 | List> added = Observable.from(pair.second.getAdded())
33 | .filter(itemRef -> predicate.call(itemRef.getValue()))
34 | .toList()
35 | .toBlocking()
36 | .first();
37 | List> updated = Observable.from(pair.second.getUpdated())
38 | .filter(itemRef -> predicate.call(itemRef.getValue()))
39 | .toList()
40 | .toBlocking()
41 | .first();
42 | List> removed = Observable.from(pair.second.getRemoved())
43 | .filter(itemRef -> predicate.call(itemRef.getValue()))
44 | .toList()
45 | .toBlocking()
46 | .first();
47 | //
48 | storageChange = new StorageChange<>(added, updated, removed);
49 | return new Pair<>(result, storageChange);
50 | };
51 | }
52 |
53 | public Func1, StorageChange>, Pair, StorageChange>> getFilter() {
54 | return filter;
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/droidsnapper-sample-rx/src/main/java/com/example/snapper/rx/util/SnapperChangeMapper.java:
--------------------------------------------------------------------------------
1 | package com.example.snapper.rx.util;
2 |
3 | import android.util.Pair;
4 |
5 | import java.util.List;
6 |
7 | import io.techery.snapper.model.Indexable;
8 | import io.techery.snapper.model.ItemRef;
9 | import io.techery.snapper.storage.StorageChange;
10 | import rx.Observable;
11 | import rx.Observable.Transformer;
12 | import rx.functions.Func1;
13 |
14 | public class SnapperChangeMapper implements Transformer, StorageChange>, Pair, StorageChange>> {
15 |
16 | private final Func1 func;
17 |
18 | public SnapperChangeMapper(Func1 func) {
19 | this.func = func;
20 | }
21 |
22 | @Override
23 | public Observable, StorageChange>> call(Observable, StorageChange>> source) {
24 | return source.map(pair -> {
25 | List list = Observable.from(pair.first).map(func).toList().toBlocking().first();
26 | List> added = Observable.from(pair.second.getAdded())
27 | .map((ItemRef itemRef) -> new ItemRef<>(itemRef.getKey(), func.call(itemRef.getValue())))
28 | .toList()
29 | .toBlocking()
30 | .first();
31 | List> updated = Observable.from(pair.second.getUpdated())
32 | .map((ItemRef itemRef) -> new ItemRef<>(itemRef.getKey(), func.call(itemRef.getValue())))
33 | .toList()
34 | .toBlocking()
35 | .first();
36 | List> removed = Observable.from(pair.second.getRemoved())
37 | .map((ItemRef itemRef) -> new ItemRef<>(itemRef.getKey(), func.call(itemRef.getValue())))
38 | .toList()
39 | .toBlocking()
40 | .first();
41 | return new Pair<>(list, new StorageChange<>(added, updated, removed));
42 | });
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/droidsnapper-sample-rx/src/main/java/com/example/snapper/rx/util/SnapperChangeSort.java:
--------------------------------------------------------------------------------
1 | package com.example.snapper.rx.util;
2 |
3 | import android.util.Pair;
4 |
5 | import java.util.Collections;
6 | import java.util.List;
7 |
8 | import io.techery.snapper.model.Indexable;
9 | import io.techery.snapper.model.ItemRef;
10 | import io.techery.snapper.storage.StorageChange;
11 | import rx.Observable;
12 | import rx.Observable.Transformer;
13 | import rx.functions.Func1;
14 | import rx.functions.Func2;
15 |
16 | public class SnapperChangeSort implements Transformer, StorageChange>, Pair, StorageChange>> {
17 |
18 | private final Func1, StorageChange>, Pair, StorageChange>> comparator;
19 |
20 | public SnapperChangeSort(Func2 comparator) {
21 | this.comparator = createComparator(comparator);
22 | }
23 |
24 | @Override
25 | public Observable, StorageChange>> call(Observable, StorageChange>> source) {
26 | return source.map(this.comparator::call);
27 |
28 | }
29 |
30 | private Func1, StorageChange>, Pair, StorageChange>> createComparator(Func2 comparator) {
31 | return pair -> {
32 | List list = Observable.from(pair.first).toSortedList(comparator).toBlocking().first();
33 | List> added = Collections.emptyList();
34 | List> removed = Collections.emptyList();
35 | List> updated = Observable.from(list).map(i -> ItemRef.make(i)).toList().toBlocking().first();
36 |
37 | return new Pair<>(list, new StorageChange<>(added, updated, removed));
38 | };
39 | }
40 |
41 | public Func1, StorageChange>, Pair, StorageChange>> getComparator() {
42 | return comparator;
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/droidsnapper-sample-rx/src/main/project.properties:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/techery/snapper/257c8504707879dbcd4b4c3981c2dde37f373ba3/droidsnapper-sample-rx/src/main/project.properties
--------------------------------------------------------------------------------
/droidsnapper-sample-rx/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
11 |
12 |
18 |
19 |
25 |
26 |
32 |
33 |
39 |
40 |
46 |
47 |
48 |
49 |
60 |
61 |
62 |
--------------------------------------------------------------------------------
/droidsnapper-sample-rx/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/techery/snapper/257c8504707879dbcd4b4c3981c2dde37f373ba3/droidsnapper-sample-rx/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/droidsnapper-sample-rx/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/techery/snapper/257c8504707879dbcd4b4c3981c2dde37f373ba3/droidsnapper-sample-rx/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/droidsnapper-sample-rx/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/techery/snapper/257c8504707879dbcd4b4c3981c2dde37f373ba3/droidsnapper-sample-rx/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/droidsnapper-sample-rx/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/techery/snapper/257c8504707879dbcd4b4c3981c2dde37f373ba3/droidsnapper-sample-rx/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/droidsnapper-sample-rx/src/main/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 64dp
6 |
7 |
--------------------------------------------------------------------------------
/droidsnapper-sample-rx/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 16dp
5 |
6 |
--------------------------------------------------------------------------------
/droidsnapper-sample-rx/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | DroidSnapper Rx Sample
3 |
4 |
--------------------------------------------------------------------------------
/droidsnapper-sample-rx/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/droidsnapper-sample/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion rootProject.ext.compileSdkVersion
5 | buildToolsVersion rootProject.ext.buildToolsVersion
6 |
7 | defaultConfig {
8 | applicationId "com.example.droidsnapper"
9 | minSdkVersion rootProject.ext.minSdkVersion
10 | targetSdkVersion rootProject.ext.targetSdkVersion
11 | }
12 |
13 | buildTypes {
14 | release {
15 | minifyEnabled false
16 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
17 | }
18 | }
19 |
20 | compileOptions {
21 | sourceCompatibility JavaVersion.VERSION_1_7
22 | targetCompatibility JavaVersion.VERSION_1_7
23 | }
24 | }
25 |
26 | repositories {
27 | jcenter()
28 | }
29 |
30 | dependencies {
31 | compile project(':droidsnapper')
32 | //
33 | compile 'com.android.support:appcompat-v7:23.3.0'
34 | //
35 | compile 'com.jakewharton:butterknife:7.0.1'
36 | compile 'com.jakewharton.timber:timber:4.1.2'
37 | }
38 |
--------------------------------------------------------------------------------
/droidsnapper-sample/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Users/zen/Library/Android/sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
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 | #}
18 |
--------------------------------------------------------------------------------
/droidsnapper-sample/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
13 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/droidsnapper-sample/src/main/java/com/example/snapper/App.java:
--------------------------------------------------------------------------------
1 | package com.example.snapper;
2 |
3 | import android.app.Application;
4 | import android.content.Context;
5 |
6 | import timber.log.Timber;
7 | import timber.log.Timber.DebugTree;
8 |
9 | public class App extends Application {
10 |
11 | @Override
12 | public void onCreate() {
13 | super.onCreate();
14 | instance = this;
15 |
16 | if (BuildConfig.DEBUG) {
17 | Timber.plant(new DebugTree());
18 | } else {
19 | // TODO Crashlytics.start(this);
20 | // TODO Timber.plant(new CrashlyticsTree());
21 | }
22 |
23 | }
24 |
25 | ///////////////////////////////////////////////////////////////////////////
26 | // Static helper
27 | ///////////////////////////////////////////////////////////////////////////
28 |
29 | public static App from(Context context) { return (App) context.getApplicationContext(); }
30 |
31 | private static App instance;
32 |
33 | public static App instance() {
34 | return instance;
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/droidsnapper-sample/src/main/java/com/example/snapper/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.example.snapper;
2 |
3 | import android.os.Bundle;
4 | import android.support.v7.app.AppCompatActivity;
5 | import android.widget.ListView;
6 |
7 | import com.innahema.collections.query.functions.Predicate;
8 |
9 | import java.nio.ByteBuffer;
10 | import java.util.ArrayList;
11 | import java.util.Comparator;
12 | import java.util.List;
13 |
14 | import butterknife.ButterKnife;
15 | import butterknife.OnClick;
16 | import io.techery.snapper.datacollection.DataCollection;
17 | import io.techery.snapper.dataset.IDataSet;
18 | import io.techery.snapper.droidsnapper.DroidSnapper;
19 | import io.techery.snapper.model.Indexable;
20 | import io.techery.snapper.projection.IProjection;
21 | import io.techery.snapper.storage.StorageChange;
22 |
23 |
24 | public class MainActivity extends AppCompatActivity {
25 |
26 | DataCollection dataCollection;
27 | IProjection sortedProjection;
28 | ProjectionArrayAdapter itemsAdapter;
29 | volatile int lastId;
30 |
31 | static final int BATCH_PUT_COUNT = 10000;
32 |
33 | @Override
34 | protected void onCreate(Bundle savedInstanceState) {
35 | super.onCreate(savedInstanceState);
36 | setContentView(R.layout.activity_main);
37 | ButterKnife.bind(this);
38 |
39 | dataCollection = DroidSnapper.with(this).collection(User.class);
40 |
41 | sortedProjection = dataCollection.projection().sort(new Comparator() {
42 | @Override
43 | public int compare(User o1, User o2) {
44 | if (o1.id < o2.id) {
45 | return 1;
46 | } else if (o1.id > o2.id) {
47 | return -1;
48 | } else {
49 | return 0;
50 | }
51 | }
52 | }).build();
53 |
54 | sortedProjection.addDataListener(new IDataSet.DataListener() {
55 | @Override
56 | public void onDataUpdated(List items, StorageChange change) {
57 | if (!items.isEmpty()) {
58 | lastId = items.get(0).id;
59 | } else {
60 | lastId = 0;
61 | }
62 | }
63 | });
64 |
65 | itemsAdapter = new ProjectionArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, sortedProjection);
66 | ListView listView = (ListView) findViewById(R.id.listView);
67 | listView.setAdapter(itemsAdapter);
68 | }
69 |
70 | @Override
71 | protected void onDestroy() {
72 | sortedProjection.close();
73 | super.onDestroy();
74 | }
75 |
76 | @OnClick(R.id.add)
77 | void onAddClick() {
78 | dataCollection.insert(genUser(lastId + 1));
79 | }
80 |
81 | @OnClick(R.id.add_many)
82 | void onAddManyClick() {
83 | List users = new ArrayList<>();
84 | int lastId = this.lastId + 1;
85 | for (int i = 0; i < BATCH_PUT_COUNT; i++) {
86 | users.add(genUser(lastId + i));
87 | }
88 | dataCollection.insertAll(users);
89 | }
90 |
91 | @OnClick(R.id.filter)
92 | void onFilterClick() {
93 | if (itemsAdapter.getProjection().equals(sortedProjection)) {
94 | itemsAdapter.setProjection(sortedProjection.projection()
95 | .where(new Predicate() {
96 | @Override
97 | public boolean apply(User element) {
98 | return element.id % 10 == 0;
99 | }
100 | })
101 | .build()
102 | );
103 | } else {
104 | itemsAdapter.setProjection(sortedProjection);
105 | }
106 | }
107 |
108 | @OnClick(R.id.clear)
109 | void onClearClick() {
110 | dataCollection.clear();
111 | }
112 |
113 | ///////////////////////////////////////////////////////////////////////////
114 | // User model
115 | ///////////////////////////////////////////////////////////////////////////
116 |
117 | static User genUser(int i) {
118 | User u = new User(i);
119 | u.email = String.valueOf(Math.random() * 100);
120 | u.name = String.valueOf(Math.random() * 100);
121 | u.price = (float) Math.random();
122 | u.isActive = Math.random() % 2 == 0;
123 | return u;
124 | }
125 |
126 | public static class User implements Indexable {
127 | public int id;
128 | public String name;
129 | public float price;
130 | public String email;
131 |
132 | public boolean isActive;
133 |
134 | public User() {
135 | }
136 |
137 | public User(int id) {
138 | this.id = id;
139 | }
140 |
141 | @Override
142 | public byte[] index() {
143 | return ByteBuffer.allocate(4).putInt(id).array();
144 | }
145 |
146 | @Override
147 | public boolean equals(Object o) {
148 | if (this == o) return true;
149 | if (o == null || getClass() != o.getClass()) return false;
150 |
151 | User user = (User) o;
152 |
153 | return id == user.id;
154 |
155 | }
156 |
157 | @Override
158 | public int hashCode() {
159 | return id;
160 | }
161 |
162 | public int getId() {
163 | return id;
164 | }
165 |
166 | public void setId(int id) {
167 | this.id = id;
168 | }
169 |
170 | public String getName() {
171 | return name;
172 | }
173 |
174 | public void setName(String name) {
175 | this.name = name;
176 | }
177 |
178 | public float getPrice() {
179 | return price;
180 | }
181 |
182 | public void setPrice(float price) {
183 | this.price = price;
184 | }
185 |
186 | public String getEmail() {
187 | return email;
188 | }
189 |
190 | public void setEmail(String email) {
191 | this.email = email;
192 | }
193 |
194 | public boolean isActive() {
195 | return isActive;
196 | }
197 |
198 | public void setIsActive(boolean isActive) {
199 | this.isActive = isActive;
200 | }
201 |
202 | @Override
203 | public String toString() {
204 | return "User{" +
205 | "id=" + id +
206 | '}';
207 | }
208 |
209 | }
210 | }
211 |
--------------------------------------------------------------------------------
/droidsnapper-sample/src/main/java/com/example/snapper/ProjectionArrayAdapter.java:
--------------------------------------------------------------------------------
1 | package com.example.snapper;
2 |
3 | import android.content.Context;
4 | import android.widget.ArrayAdapter;
5 |
6 | import java.util.List;
7 |
8 | import io.techery.snapper.dataset.IDataSet;
9 | import io.techery.snapper.droidsnapper.helper.MainThreadDataListener;
10 | import io.techery.snapper.projection.IProjection;
11 | import io.techery.snapper.storage.StorageChange;
12 | import timber.log.Timber;
13 |
14 | public class ProjectionArrayAdapter extends ArrayAdapter implements IDataSet.DataListener {
15 |
16 | private IProjection projection;
17 |
18 | public ProjectionArrayAdapter(Context context, int resource, IProjection projection) {
19 | super(context, resource);
20 | setProjection(projection);
21 | }
22 |
23 | public IProjection getProjection() {
24 | return projection;
25 | }
26 |
27 | public void setProjection(IProjection projection) {
28 | if (this.projection != null) {
29 | this.projection.removeDataListener(this);
30 | }
31 |
32 | this.projection = projection;
33 | this.projection.addDataListener(new MainThreadDataListener(this));
34 | }
35 |
36 | @Override
37 | public void onDataUpdated(List items, StorageChange change) {
38 | syncWithProjection(items);
39 | notifyDataSetChanged();
40 | }
41 |
42 | private void syncWithProjection(List items) {
43 | clear();
44 | addAll(items);
45 | Timber.d("Synced items: %d", items.size());
46 | }
47 |
48 | }
49 |
--------------------------------------------------------------------------------
/droidsnapper-sample/src/main/project.properties:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/techery/snapper/257c8504707879dbcd4b4c3981c2dde37f373ba3/droidsnapper-sample/src/main/project.properties
--------------------------------------------------------------------------------
/droidsnapper-sample/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
12 |
13 |
19 |
20 |
26 |
27 |
33 |
34 |
40 |
41 |
47 |
48 |
49 |
50 |
58 |
59 |
60 |
--------------------------------------------------------------------------------
/droidsnapper-sample/src/main/res/layout/user_cell.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
14 |
--------------------------------------------------------------------------------
/droidsnapper-sample/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/techery/snapper/257c8504707879dbcd4b4c3981c2dde37f373ba3/droidsnapper-sample/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/droidsnapper-sample/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/techery/snapper/257c8504707879dbcd4b4c3981c2dde37f373ba3/droidsnapper-sample/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/droidsnapper-sample/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/techery/snapper/257c8504707879dbcd4b4c3981c2dde37f373ba3/droidsnapper-sample/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/droidsnapper-sample/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/techery/snapper/257c8504707879dbcd4b4c3981c2dde37f373ba3/droidsnapper-sample/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/droidsnapper-sample/src/main/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 64dp
6 |
7 |
--------------------------------------------------------------------------------
/droidsnapper-sample/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 16dp
5 |
6 |
--------------------------------------------------------------------------------
/droidsnapper-sample/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | DroidSnapper Sample
3 |
4 |
--------------------------------------------------------------------------------
/droidsnapper-sample/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/droidsnapper/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/droidsnapper/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 | apply plugin: 'com.github.dcendents.android-maven'
3 | apply plugin: 'com.github.ben-manes.versions'
4 |
5 | android {
6 | compileSdkVersion rootProject.ext.compileSdkVersion
7 | buildToolsVersion rootProject.ext.buildToolsVersion
8 |
9 | defaultConfig {
10 | minSdkVersion rootProject.ext.minSdkVersion
11 | targetSdkVersion rootProject.ext.targetSdkVersion
12 |
13 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
14 | }
15 | dexOptions {
16 | preDexLibraries = rootProject.ext.preDexLibs
17 | }
18 | compileOptions {
19 | sourceCompatibility JavaVersion.VERSION_1_6
20 | targetCompatibility JavaVersion.VERSION_1_6
21 | }
22 | packagingOptions {
23 | exclude 'LICENSE'
24 | exclude 'LICENSE.txt'
25 | }
26 | }
27 |
28 | repositories {
29 | jcenter()
30 | maven { url "http://dl.bintray.com/kucherenko-alex/android" }
31 | }
32 |
33 | dependencies {
34 | compile project(':snapper')
35 | compile project(':snapper-converters:kryo')
36 | compile(project(':snapper-persisters:snappydb')) {
37 | exclude group: 'com.esotericsoftware.kryo', module: 'kryo'
38 | }
39 | //
40 | androidTestCompile('com.android.support.test:runner:0.5')
41 | androidTestCompile('com.android.support.test:rules:0.5')
42 | androidTestCompile 'com.android.support:support-annotations:23.3.0'
43 | //
44 | androidTestCompile 'org.mockito:mockito-core:2.0.10-beta'
45 | androidTestCompile 'com.google.dexmaker:dexmaker:1.2'
46 | androidTestCompile 'com.google.dexmaker:dexmaker-mockito:1.2'
47 | androidTestCompile 'com.artfulbits:meter:1.0.1.164'
48 | androidTestCompile 'net.jodah:concurrentunit:0.4.2'
49 | androidTestCompile 'com.jakewharton.timber:timber:4.1.2'
50 | }
51 |
52 | task sourcesJar(type: Jar) {
53 | classifier = 'sources'
54 | from android.sourceSets.main.java.srcDirs
55 | }
56 |
57 | task javadoc(type: Javadoc) {
58 | source = android.sourceSets.main.java.srcDirs
59 | classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
60 | }
61 |
62 | task javadocJar(type: Jar, dependsOn: javadoc) {
63 | classifier = 'javadoc'
64 | from javadoc.destinationDir
65 | }
66 |
67 | artifacts {
68 | archives sourcesJar
69 | archives javadocJar
70 | }
71 |
--------------------------------------------------------------------------------
/droidsnapper/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Users/almozavr/android/system/android-sdk-macosx/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
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 | #}
18 |
--------------------------------------------------------------------------------
/droidsnapper/src/androidTest/java/io/techery/snapper/BaseAsyncTestCase.java:
--------------------------------------------------------------------------------
1 | package io.techery.snapper;
2 |
3 |
4 | import net.jodah.concurrentunit.Waiter;
5 |
6 | import java.util.concurrent.ExecutorService;
7 | import java.util.concurrent.Executors;
8 | import java.util.concurrent.atomic.AtomicInteger;
9 |
10 | import io.techery.snapper.executor.SnapperThreadFactory;
11 | import timber.log.Timber;
12 |
13 | public class BaseAsyncTestCase extends BaseTestCase {
14 |
15 | @Override public void prepareDb() {
16 | super.prepareDb();
17 | }
18 |
19 | @Override protected ExecutorService provideStorageExecutor() {
20 | return Executors.newSingleThreadExecutor(new SnapperThreadFactory("storage"));
21 | }
22 |
23 | @Override protected ExecutorService provideCollectionExecutor() {
24 | return Executors.newFixedThreadPool(4, new SnapperThreadFactory("collection"));
25 | }
26 |
27 | ///////////////////////////////////////////////////////////////////////////
28 | // Waiter for concurrency
29 | ///////////////////////////////////////////////////////////////////////////
30 |
31 | protected Waiter waiter = new Waiter();
32 | private AtomicInteger expectedResumes = new AtomicInteger();
33 |
34 | protected void expectResumes(int count) {
35 | expectedResumes.addAndGet(count);
36 | }
37 |
38 | protected void await() {
39 | try {
40 | waiter.await(0, expectedResumes.get());
41 | } catch (Throwable throwable) {
42 | Timber.w(throwable, "Can't wait :(");
43 | }
44 | }
45 |
46 | protected void resume() {
47 | expectedResumes.decrementAndGet();
48 | waiter.resume();
49 | }
50 |
51 | protected void runWithAwait(int resumes, Runnable command) {
52 | expectResumes(resumes);
53 | command.run();
54 | await();
55 | }
56 |
57 | }
58 |
--------------------------------------------------------------------------------
/droidsnapper/src/androidTest/java/io/techery/snapper/BaseSyncTestCase.java:
--------------------------------------------------------------------------------
1 | package io.techery.snapper;
2 |
3 | import java.util.concurrent.ExecutorService;
4 |
5 | import io.techery.snapper.executor.SimpleExecutorService;
6 |
7 | public class BaseSyncTestCase extends BaseTestCase {
8 |
9 | private ExecutorService createSimpleExecutor() {
10 | return new SimpleExecutorService() {
11 | @Override public void execute(Runnable command) {
12 | command.run();
13 | }
14 | };
15 | }
16 |
17 | @Override protected ExecutorService provideStorageExecutor() {
18 | return createSimpleExecutor();
19 | }
20 |
21 | @Override protected ExecutorService provideCollectionExecutor() {
22 | return createSimpleExecutor();
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/droidsnapper/src/androidTest/java/io/techery/snapper/BaseTestCase.java:
--------------------------------------------------------------------------------
1 | package io.techery.snapper;
2 |
3 | import android.content.Context;
4 | import android.support.test.InstrumentationRegistry;
5 |
6 | import org.junit.After;
7 | import org.junit.Before;
8 |
9 | import java.util.concurrent.ExecutorService;
10 |
11 | import io.techery.snapper.executor.FixedExecutorFactory;
12 | import timber.log.Timber;
13 |
14 | import static io.techery.snapper.droidsnapper.DroidSnapper.Builder;
15 |
16 | public abstract class BaseTestCase {
17 |
18 | static {
19 | Timber.plant(new Timber.DebugTree());
20 | }
21 |
22 | protected Snapper db;
23 |
24 | @Before
25 | public void prepareDb() {
26 | Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();
27 | //
28 | Builder builder = new Builder(context);
29 | builder.storageFileName("snappydb_test");
30 | builder.collectionExecutor(new FixedExecutorFactory(provideCollectionExecutor()));
31 | builder.storageExecutor(new FixedExecutorFactory(provideStorageExecutor()));
32 | //
33 | db = builder.build();
34 | }
35 |
36 | @After
37 | public void clearDb() {
38 | db.clear();
39 | }
40 |
41 | protected abstract ExecutorService provideStorageExecutor();
42 |
43 | protected abstract ExecutorService provideCollectionExecutor();
44 | }
45 |
--------------------------------------------------------------------------------
/droidsnapper/src/androidTest/java/io/techery/snapper/model/Company.java:
--------------------------------------------------------------------------------
1 | package io.techery.snapper.model;
2 |
3 | import java.nio.ByteBuffer;
4 | import java.util.List;
5 |
6 | public class Company implements Indexable {
7 |
8 | int id;
9 | String name;
10 | List users;
11 |
12 | public Company(int id, String name, List users) {
13 | this.id = id;
14 | this.name = name;
15 | this.users = users;
16 | }
17 |
18 | @Override public byte[] index() {
19 | return ByteBuffer.allocate(4).putInt(id).array();
20 | }
21 |
22 | @Override public boolean equals(Object o) {
23 | if (this == o) return true;
24 | if (o == null || getClass() != o.getClass()) return false;
25 |
26 | Company company = (Company) o;
27 |
28 | return id == company.id;
29 |
30 | }
31 |
32 | @Override public int hashCode() {
33 | return id;
34 | }
35 |
36 | public int getId() {
37 | return id;
38 | }
39 |
40 | public void setId(int id) {
41 | this.id = id;
42 | }
43 |
44 | public String getName() {
45 | return name;
46 | }
47 |
48 | public void setName(String name) {
49 | this.name = name;
50 | }
51 |
52 | public List getUsers() {
53 | return users;
54 | }
55 |
56 | public void setUsers(List users) {
57 | this.users = users;
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/droidsnapper/src/androidTest/java/io/techery/snapper/model/User.java:
--------------------------------------------------------------------------------
1 | package io.techery.snapper.model;
2 |
3 | public class User implements Indexable {
4 |
5 | private String userId;
6 | private int age = 100;
7 | private int companyId;
8 |
9 | @Override
10 | public byte[] index() {
11 | return userId.getBytes();
12 | }
13 |
14 | public User(String userId) {
15 | this.userId = userId;
16 | }
17 |
18 | public User(String userId, int age) {
19 | this.userId = userId;
20 | this.age = age;
21 | }
22 |
23 | public User(String userId, int age, int companyId) {
24 | this.userId = userId;
25 | this.age = age;
26 | this.companyId = companyId;
27 | }
28 |
29 | @Override public boolean equals(Object o) {
30 | if (this == o) return true;
31 | if (o == null || getClass() != o.getClass()) return false;
32 |
33 | User user = (User) o;
34 |
35 | if (userId != null ? !userId.equals(user.userId) : user.userId != null) return false;
36 |
37 | return true;
38 | }
39 |
40 | @Override public int hashCode() {
41 | return userId != null ? userId.hashCode() : 0;
42 | }
43 |
44 | public String getUserId() {
45 | return userId;
46 | }
47 |
48 | public void setUserId(String userId) {
49 | this.userId = userId;
50 | }
51 |
52 | public int getAge() {
53 | return age;
54 | }
55 |
56 | public void setAge(int age) {
57 | this.age = age;
58 | }
59 |
60 | public int getCompanyId() {
61 | return companyId;
62 | }
63 |
64 | public void setCompanyId(int companyId) {
65 | this.companyId = companyId;
66 | }
67 |
68 | @Override public String toString() {
69 | return "User{" +
70 | "userId='" + userId + '\'' +
71 | ", age=" + age +
72 | ", companyId=" + companyId +
73 | '}';
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/droidsnapper/src/androidTest/java/io/techery/snapper/test/BasicOperationsTest.java:
--------------------------------------------------------------------------------
1 | package io.techery.snapper.test;
2 |
3 | import android.support.test.runner.AndroidJUnit4;
4 |
5 | import com.innahema.collections.query.functions.Function1;
6 | import com.innahema.collections.query.functions.Predicate;
7 | import com.innahema.collections.query.queriables.Queryable;
8 |
9 | import org.junit.After;
10 | import org.junit.Before;
11 | import org.junit.Rule;
12 | import org.junit.Test;
13 | import org.junit.rules.ExpectedException;
14 | import org.junit.runner.RunWith;
15 |
16 | import java.util.Comparator;
17 | import java.util.List;
18 |
19 | import io.techery.snapper.BaseSyncTestCase;
20 | import io.techery.snapper.datacollection.DataCollection;
21 | import io.techery.snapper.dataset.DataSetMap;
22 | import io.techery.snapper.dataset.IDataSet.StatusListener;
23 | import io.techery.snapper.model.User;
24 | import io.techery.snapper.projection.IProjection;
25 | import io.techery.snapper.projection.ProjectionBuilder;
26 | import io.techery.snapper.util.ModelUtil;
27 |
28 | import static org.hamcrest.CoreMatchers.equalTo;
29 | import static org.hamcrest.CoreMatchers.is;
30 | import static org.junit.Assert.assertThat;
31 | import static org.junit.Assert.assertTrue;
32 | import static org.junit.matchers.JUnitMatchers.hasItem;
33 | import static org.mockito.Mockito.mock;
34 | import static org.mockito.Mockito.only;
35 | import static org.mockito.Mockito.verify;
36 |
37 | @RunWith(AndroidJUnit4.class)
38 | public class BasicOperationsTest extends BaseSyncTestCase {
39 |
40 | DataCollection dataCollection;
41 | IProjection filteredProjection;
42 |
43 | ///////////////////////////////////////////////////////////////////////////
44 | // Preconditions
45 | ///////////////////////////////////////////////////////////////////////////
46 |
47 | @Before
48 | public void createCollectionAndFilter() {
49 | dataCollection = db.collection(User.class);
50 | filteredProjection = dataCollection.projection()
51 | .where(new Predicate() {
52 | @Override
53 | public boolean apply(User element) {
54 | return element.getUserId().length() > 3;
55 | }
56 | }).sort(new Comparator() {
57 | @Override
58 | public int compare(User o1, User o2) {
59 | return o1.getUserId().compareTo(o2.getUserId());
60 | }
61 | })
62 | .build();
63 | }
64 |
65 | @After
66 | public void releaseCollection() throws Exception {
67 | if (!dataCollection.isClosed()) {
68 | dataCollection.clear();
69 | dataCollection.close();
70 | }
71 | }
72 |
73 | ///////////////////////////////////////////////////////////////////////////
74 | // Tests
75 | ///////////////////////////////////////////////////////////////////////////
76 |
77 | @Test
78 | public void oneModelManyCollections() {
79 | dataCollection = db.collection(User.class);
80 | insertUsers();
81 | assertThat(dataCollection.size(), is(5));
82 |
83 | dataCollection = db.collection(User.class, "guest");
84 | assertThat(dataCollection.size(), is(0));
85 | }
86 |
87 | @Test
88 | public void loadCollection() {
89 | dataCollection.insertAll(ModelUtil.generateUsers(1000));
90 | dataCollection.close();
91 | dataCollection = db.collection(User.class);
92 | assertThat(Queryable.from(dataCollection).count(), is(1000));
93 | }
94 |
95 | @Test
96 | public void buildFilteredProjection() {
97 | insertUsers();
98 | IProjection filtered = dataCollection.projection().where(new Predicate() {
99 | @Override
100 | public boolean apply(User element) {
101 | return element.getUserId().length() > 3;
102 | }
103 | }).build();
104 |
105 | assertThat("Filtered Projection should have 2 elements with length > 3", filtered.size(), is(2));
106 | }
107 |
108 | @Test
109 | public void buildSortedProjection() {
110 | insertUsers();
111 | IProjection sorted = dataCollection.projection().sort(new Comparator() {
112 | @Override
113 | public int compare(User o1, User o2) {
114 | return o1.getUserId().compareTo(o2.getUserId());
115 | }
116 | }).build();
117 |
118 | assertThat("Sorted Projection should have 5 elements", sorted.size(), is(5));
119 | assertThat(sorted.getItem(0).getUserId(), equalTo("1"));
120 | assertThat(sorted.getItem(1).getUserId(), equalTo("10"));
121 | assertThat(sorted.getItem(2).getUserId(), equalTo("100"));
122 | assertThat(sorted.getItem(3).getUserId(), equalTo("1000"));
123 | assertThat(sorted.getItem(4).getUserId(), equalTo("10000"));
124 | }
125 |
126 | @Test
127 | public void addOne() {
128 | insertUsers();
129 | assertThat("Filtered Projection should have 3 elements with length > 3", filteredProjection.size(), is(2));
130 |
131 | dataCollection.insert(new User("100000"));
132 | assertThat("Filtered Projection should have 3 elements with length > 3", filteredProjection.size(), is(3));
133 | List ids = ModelUtil.extractUserIds(filteredProjection);
134 | assertThat(ids, hasItem("1000"));
135 | assertThat(ids, hasItem("10000"));
136 | assertThat(ids, hasItem("100000"));
137 | }
138 |
139 | @Test
140 | public void removeOne() {
141 | insertUsers();
142 | dataCollection.remove(new User("1000"));
143 |
144 | assertThat("should have 2 elements", filteredProjection.size(), is(1));
145 | assertThat(filteredProjection.getItem(0).getUserId(), equalTo("10000"));
146 | }
147 |
148 | @Test
149 | public void updateOne() {
150 | insertUsers();
151 | IProjection filtered = dataCollection.projection()
152 | .where(new Predicate() {
153 | @Override
154 | public boolean apply(User element) {
155 | return element.getAge() > 100 && element.getUserId().length() > 3;
156 | }
157 | }).sort(new Comparator() {
158 | @Override
159 | public int compare(User o1, User o2) {
160 | return o1.getUserId().compareTo(o2.getUserId());
161 | }
162 | })
163 | .build();
164 |
165 | String userId = "1000";
166 |
167 | dataCollection.insert(new User(userId, 10));
168 | assertThat("Filtered Projection should have 0 elements with age > 100", filtered.size(), is(0));
169 |
170 | dataCollection.insert(new User(userId, 400));
171 | List ids = ModelUtil.extractUserIds(filtered);
172 | assertThat("Filtered Projection should have 1 elements with age > 100", filtered.size(), is(1));
173 | assertThat(ids, hasItem(userId));
174 | List ages = ModelUtil.extractAges(filtered);
175 | assertThat(ages, hasItem(400));
176 | List storageAges = ModelUtil.extractAges(dataCollection);
177 | assertThat(storageAges, hasItem(400));
178 | }
179 |
180 | @Test
181 | public void buildMappedDataSet() {
182 | insertUsers();
183 | DataSetMap dataSetMap = new DataSetMap(dataCollection, new Function1() {
184 | @Override
185 | public Integer apply(User s) {
186 | return s.getUserId().length();
187 | }
188 | });
189 |
190 | IProjection dv = new ProjectionBuilder(dataSetMap).sort(new Comparator() {
191 | @Override
192 | public int compare(Integer o1, Integer o2) {
193 | return o1.compareTo(o2);
194 | }
195 | }).build();
196 |
197 | assertThat("should have 5 elements", dv.size(), is(5));
198 | assertThat(dv.getItem(0), is(1));
199 | assertThat(dv.getItem(1), is(2));
200 | assertThat(dv.getItem(2), is(3));
201 | assertThat(dv.getItem(3), is(4));
202 | assertThat(dv.getItem(4), is(5));
203 |
204 | String item = "12313123";
205 | dataCollection.insert(new User(item));
206 |
207 | assertThat("should have 5 elements", dv.size(), is(6));
208 | }
209 |
210 | @Rule
211 | public ExpectedException thrown = ExpectedException.none();
212 |
213 | @Test
214 | public void closeAll() {
215 | db.close();
216 | assertTrue(dataCollection.isClosed());
217 | assertTrue(filteredProjection.isClosed());
218 | }
219 |
220 | @Test
221 | public void collectionAfterClose() {
222 | db.close();
223 | thrown.expect(IllegalStateException.class);
224 | dataCollection.insert(new User("123123"));
225 | }
226 |
227 | @Test
228 | public void projectionAfterClose() {
229 | StatusListener mockListener = mock(StatusListener.class);
230 | filteredProjection.addStatusListener(mockListener);
231 | db.close();
232 | verify(mockListener, only()).onClosed();
233 | //
234 | thrown.expect(IllegalStateException.class);
235 | filteredProjection.toList();
236 | }
237 |
238 | ///////////////////////////////////////////////////////////////////////////
239 | // Helpers
240 | ///////////////////////////////////////////////////////////////////////////
241 |
242 | private void insertUsers() {
243 | dataCollection.insert(new User("10000"));
244 | dataCollection.insert(new User("100"));
245 | dataCollection.insert(new User("1"));
246 | dataCollection.insert(new User("10"));
247 | dataCollection.insert(new User("1000"));
248 | }
249 |
250 | }
--------------------------------------------------------------------------------
/droidsnapper/src/androidTest/java/io/techery/snapper/test/HelpersTest.java:
--------------------------------------------------------------------------------
1 | package io.techery.snapper.test;
2 |
3 | import android.os.Handler;
4 | import android.os.Looper;
5 | import android.support.test.runner.AndroidJUnit4;
6 |
7 | import com.innahema.collections.query.functions.Predicate;
8 |
9 | import net.jodah.concurrentunit.Waiter;
10 |
11 | import org.junit.After;
12 | import org.junit.Before;
13 | import org.junit.Test;
14 | import org.junit.runner.RunWith;
15 |
16 | import java.util.List;
17 |
18 | import io.techery.snapper.BaseSyncTestCase;
19 | import io.techery.snapper.datacollection.DataCollection;
20 | import io.techery.snapper.dataset.IDataSet.DataListener;
21 | import io.techery.snapper.model.User;
22 | import io.techery.snapper.projection.IProjection;
23 | import io.techery.snapper.storage.StorageChange;
24 | import io.techery.snapper.droidsnapper.helper.MainThreadDataListener;
25 | import io.techery.snapper.helper.SingleItemDataListener;
26 | import io.techery.snapper.helper.SingleItemDataListener.ChangeStatus;
27 |
28 | import static org.hamcrest.CoreMatchers.is;
29 | import static org.hamcrest.CoreMatchers.nullValue;
30 | import static org.junit.Assert.assertThat;
31 | import static org.junit.Assert.assertTrue;
32 |
33 | @RunWith(AndroidJUnit4.class)
34 | public class HelpersTest extends BaseSyncTestCase {
35 |
36 | private DataCollection dataCollection;
37 |
38 | @Before
39 | public void createCollection() {
40 | dataCollection = db.collection(User.class);
41 | }
42 |
43 | @After
44 | public void releaseCollection() throws Exception {
45 | if (!dataCollection.isClosed()) {
46 | dataCollection.clear();
47 | dataCollection.close();
48 | }
49 | }
50 |
51 | ///////////////////////////////////////////////////////////////////////////
52 | // Tests
53 | ///////////////////////////////////////////////////////////////////////////
54 |
55 | @Test
56 | public void mainThreadListener() throws Throwable {
57 | final Waiter waiter = new Waiter();
58 | dataCollection.insert(new User("1"));
59 | final boolean[] updatedOnMainThread = new boolean[1];
60 | final User[] user = new User[1];
61 | dataCollection.addDataListener(new MainThreadDataListener(new DataListener() {
62 | @Override public void onDataUpdated(final List items, StorageChange change) {
63 | updatedOnMainThread[0] = Thread.currentThread().getName().contains("main");
64 | user[0] = items.isEmpty() ? null : items.get(0);
65 | new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
66 | @Override public void run() {
67 | if (!items.isEmpty()) waiter.resume();
68 | }
69 | }, 100l);
70 | }
71 | }));
72 | waiter.await(0, 1);
73 | assertTrue(updatedOnMainThread[0]);
74 | assertThat(user[0].getUserId(), is("1"));
75 | }
76 |
77 | @Test
78 | public void singleItemListener() {
79 | dataCollection.insert(new User("10000"));
80 | dataCollection.insert(new User("100"));
81 | dataCollection.insert(new User("1"));
82 | //
83 | final User[] userToWatch = {null};
84 | final ChangeStatus[] changeStatus = new ChangeStatus[1];
85 | IProjection projection = dataCollection.projection()
86 | .where(new Predicate() {
87 | @Override public boolean apply(User element) {
88 | return element.getUserId().equals("10000");
89 | }
90 | }).build();
91 | projection.addDataListener(new SingleItemDataListener() {
92 | @Override protected void onItemUpdated(User user, ChangeStatus status) {
93 | userToWatch[0] = user;
94 | changeStatus[0] = status;
95 | }
96 | });
97 | // creation
98 | assertThat(userToWatch[0].getUserId(), is("10000"));
99 | assertThat(userToWatch[0].getAge(), is(100));
100 | assertThat(changeStatus[0], is(ChangeStatus.ADDED));
101 | // update
102 | dataCollection.insert(new User("10000", 50));
103 | assertThat(userToWatch[0].getAge(), is(50));
104 | assertThat(changeStatus[0], is(ChangeStatus.UPDATED));
105 | // remove
106 | dataCollection.remove(new User("10000", 50));
107 | assertThat(userToWatch[0], nullValue());
108 | assertThat(changeStatus[0], is(ChangeStatus.REMOVED));
109 | }
110 | }
111 |
--------------------------------------------------------------------------------
/droidsnapper/src/androidTest/java/io/techery/snapper/test/ManyCollectionsTest.java:
--------------------------------------------------------------------------------
1 | package io.techery.snapper.test;
2 |
3 | import android.support.test.runner.AndroidJUnit4;
4 | import android.util.Pair;
5 |
6 | import com.innahema.collections.query.functions.Function2;
7 | import com.innahema.collections.query.functions.Predicate;
8 | import com.innahema.collections.query.queriables.Queryable;
9 |
10 | import org.junit.After;
11 | import org.junit.Before;
12 | import org.junit.Test;
13 | import org.junit.runner.RunWith;
14 |
15 | import java.util.Collections;
16 | import java.util.List;
17 |
18 | import io.techery.snapper.BaseSyncTestCase;
19 | import io.techery.snapper.datacollection.DataCollection;
20 | import io.techery.snapper.dataset.DataSetJoin;
21 | import io.techery.snapper.dataset.DataSetJoin.JoinBuilder;
22 | import io.techery.snapper.model.Company;
23 | import io.techery.snapper.model.User;
24 | import io.techery.snapper.projection.IProjection;
25 |
26 | import static org.hamcrest.CoreMatchers.is;
27 | import static org.junit.Assert.assertThat;
28 | import static org.junit.Assert.assertTrue;
29 | import static org.junit.matchers.JUnitMatchers.hasItem;
30 |
31 | @RunWith(AndroidJUnit4.class)
32 | public class ManyCollectionsTest extends BaseSyncTestCase {
33 |
34 | DataCollection userStorage;
35 | DataCollection companyStorage;
36 |
37 | ///////////////////////////////////////////////////////////////////////////
38 | // Preconditions
39 | ///////////////////////////////////////////////////////////////////////////
40 |
41 | @Before public void createCollectionAndFilter() {
42 | userStorage = db.collection(User.class);
43 | userStorage.insert(new User("10000"));
44 | userStorage.insert(new User("100"));
45 | userStorage.insert(new User("1", 20, 2));
46 | userStorage.insert(new User("10", 30, 2));
47 | userStorage.insert(new User("1000"));
48 |
49 | companyStorage = db.collection(Company.class);
50 | companyStorage.insert(new Company(1, "BigCo", Collections.singletonList(new User("100"))));
51 | companyStorage.insert(new Company(2, "SmallCo", Collections.singletonList(new User("1"))));
52 | }
53 |
54 | @After public void releaseCollection() throws Exception {
55 | db.collection(User.class).clear();
56 | db.collection(Company.class).clear();
57 | }
58 |
59 | ///////////////////////////////////////////////////////////////////////////
60 | // Tests
61 | ///////////////////////////////////////////////////////////////////////////
62 |
63 | @Test public void storageConsistency() {
64 | assertThat(userStorage.projection().build().toList().size(), is(5));
65 | assertThat(companyStorage.projection().build().toList().size(), is(2));
66 | }
67 |
68 | @Test public void modelEqualityFromDiffStorages() {
69 | IProjection smallCoView = companyStorage.projection().where(new Predicate() {
70 | @Override public boolean apply(Company element) {
71 | return element.getName().contains("SmallCo");
72 | }
73 | }).build();
74 | IProjection smallCoUserView = userStorage.projection().where(new Predicate() {
75 | @Override public boolean apply(User element) {
76 | return element.getUserId().equals("1");
77 | }
78 | }).build();
79 | Company company = Queryable.from(smallCoView.toList()).first();
80 | User user = Queryable.from(smallCoUserView.toList()).first();
81 | assertThat(company.getUsers(), hasItem(user));
82 | }
83 |
84 | @Test public void join() {
85 | DataSetJoin> companyUserJoin =
86 | new JoinBuilder(companyStorage, userStorage)
87 | .setJoinFunction(new Function2() {
88 | @Override public Boolean apply(Company company, User user) {
89 | return company.getId() == user.getCompanyId();
90 | }
91 | })
92 | .setMapFunction(new Function2, Pair>() {
93 | @Override public Pair apply(Company company, List users) {
94 | User user = users.isEmpty() ? null : users.get(0);
95 | return new Pair(company, user);
96 | }
97 | }).create();
98 | int companyId = 2;
99 | User user = new User("1", 20, companyId);
100 | Company company = new Company(companyId, "SmallCo", null);
101 | assertThat(companyUserJoin.toList(), hasItem(new Pair(company, user)));
102 | assertThat(companyUserJoin.size(), is(2));
103 | }
104 |
105 | @Test public void closeAll() {
106 | db.close();
107 | assertTrue(userStorage.isClosed());
108 | assertTrue(companyStorage.isClosed());
109 | }
110 |
111 | }
--------------------------------------------------------------------------------
/droidsnapper/src/androidTest/java/io/techery/snapper/test/benchmark/PerformanceTest.java:
--------------------------------------------------------------------------------
1 | package io.techery.snapper.test.benchmark;
2 |
3 | import android.support.test.runner.AndroidJUnit4;
4 |
5 | import com.artfulbits.benchmark.Meter;
6 |
7 | import org.junit.After;
8 | import org.junit.Before;
9 | import org.junit.Test;
10 | import org.junit.runner.RunWith;
11 |
12 | import java.util.List;
13 |
14 | import io.techery.snapper.BaseAsyncTestCase;
15 | import io.techery.snapper.datacollection.DataCollection;
16 | import io.techery.snapper.dataset.IDataSet;
17 | import io.techery.snapper.dataset.IDataSet.DataListener;
18 | import io.techery.snapper.model.User;
19 | import io.techery.snapper.storage.StorageChange;
20 | import io.techery.snapper.util.ModelUtil;
21 |
22 | @RunWith(AndroidJUnit4.class)
23 | public class PerformanceTest extends BaseAsyncTestCase {
24 |
25 | DataCollection userStorage;
26 | static final int BATCH_SIZE = 10000;
27 |
28 | Meter METER;
29 | volatile boolean skipDataUpdate;
30 | MeterDataListener meterDataListener;
31 | static final String DATA_LISTENER_LOG_TAG = "Storage";
32 |
33 | @Before
34 | public void initMeter() {
35 | METER = Meter.getInstance();
36 | METER.getConfig().ShowStepCostPercents = false;
37 | METER.getConfig().ShowTopNLongest = 0;
38 | }
39 |
40 | @Before
41 | public void initStorage() {
42 | startSkippingOnChange();
43 | runWithAwait(1, new Runnable() {
44 | @Override public void run() {
45 | userStorage = db.collection(User.class);
46 | meterDataListener = new MeterDataListener(DATA_LISTENER_LOG_TAG);
47 | userStorage.addDataListener(meterDataListener);
48 | userStorage.addDataListener(new InitializeAndResumeListener(userStorage));
49 | }
50 | });
51 | }
52 |
53 | @After
54 | public void release() {
55 | startSkippingOnChange();
56 | if (userStorage.size() > 0 && !userStorage.isClosed()) {
57 | runWithAwait(1, new Runnable() {
58 | @Override public void run() {
59 | userStorage.removeDataListener(meterDataListener);
60 | userStorage.addDataListener(new DataListener() {
61 | @Override public void onDataUpdated(List items, StorageChange change) {
62 | if (!change.getRemoved().isEmpty()) resume();
63 | }
64 | });
65 | userStorage.clear();
66 | }
67 | });
68 | }
69 | db.close();
70 | stopSkippingOnChange();
71 | }
72 |
73 | ///////////////////////////////////////////////////////////////////////////
74 | // Tests
75 | ///////////////////////////////////////////////////////////////////////////
76 |
77 | @Test
78 | public void batchInsert() throws Throwable {
79 | METER.start("Batch Insert");
80 | //
81 | stopSkippingOnChange();
82 | final List users = ModelUtil.generateUsers(BATCH_SIZE);
83 | METER.skip("Generating users");
84 | //
85 | runBatchInsert(users);
86 | METER.finish("END of Batch Insert");
87 | }
88 |
89 | protected void runBatchInsert(final List users) {
90 | runWithAwait(1, new Runnable() {
91 | @Override public void run() {
92 | userStorage.insertAll(users);
93 | }
94 | });
95 | }
96 |
97 | @Test
98 | public void batchRemove() {
99 | METER.start("Batch Clear");
100 | //
101 | startSkippingOnChange();
102 | runBatchInsert(ModelUtil.generateUsers(BATCH_SIZE));
103 | //
104 | stopSkippingOnChange();
105 | runBatchRemove();
106 | METER.finish("END of Batch Clear");
107 | }
108 |
109 | protected void runBatchRemove() {
110 | runWithAwait(1, new Runnable() {
111 | @Override public void run() {
112 | userStorage.clear();
113 | }
114 | });
115 | }
116 |
117 | @Test
118 | public void load() {
119 | METER.start("Batch Load");
120 | //
121 | startSkippingOnChange();
122 | runBatchInsert(ModelUtil.generateUsers(BATCH_SIZE));
123 | db.close();
124 | userStorage = db.collection(User.class);
125 | //
126 | stopSkippingOnChange();
127 | runBatchLoad();
128 | METER.finish("END of Batch Load");
129 |
130 | }
131 |
132 | protected void runBatchLoad() {
133 | runWithAwait(1, new Runnable() {
134 | @Override public void run() {
135 | userStorage.addDataListener(meterDataListener);
136 | }
137 | });
138 | }
139 |
140 | ///////////////////////////////////////////////////////////////////////////
141 | // Helpers
142 | ///////////////////////////////////////////////////////////////////////////
143 |
144 | class MeterDataListener implements DataListener {
145 |
146 | private final String logTag;
147 |
148 | public MeterDataListener(String logTag) {
149 | this.logTag = logTag;
150 | }
151 |
152 | @Override public void onDataUpdated(List items, StorageChange change) {
153 | if (canReactOnChange(items, change)) {
154 | if (canMeterChange()) {
155 | if (skipDataUpdate) {
156 | onSkip(items, change);
157 | } else {
158 | onBeat(items, change);
159 | }
160 | }
161 | resume();
162 | }
163 | }
164 |
165 | protected void onSkip(List items, StorageChange change) {
166 | METER.skip(buildMeterLog(items, change));
167 | }
168 |
169 | protected void onBeat(List items, StorageChange change) {
170 | METER.beat(buildMeterLog(items, change));
171 | }
172 |
173 | private String buildMeterLog(List items, StorageChange change) {
174 | return logTag + " update, items count is " + items.size() + " change is " + change;
175 | }
176 | }
177 |
178 | boolean canReactOnChange(List items, StorageChange change) {
179 | return items.size() == BATCH_SIZE
180 | || change.getAdded().size() == BATCH_SIZE
181 | || change.getRemoved().size() == BATCH_SIZE
182 | || change.getUpdated().size() == BATCH_SIZE;
183 | }
184 |
185 | boolean canMeterChange() {
186 | return !(METER == null || !METER.isTracking());
187 | }
188 |
189 | void startSkippingOnChange() {
190 | skipDataUpdate = true;
191 | }
192 |
193 | void stopSkippingOnChange() {
194 | skipDataUpdate = false;
195 | }
196 |
197 | class InitializeAndResumeListener implements DataListener {
198 |
199 | IDataSet dataSet;
200 | boolean isRemoved;
201 |
202 | public InitializeAndResumeListener(IDataSet dataSet) {
203 | this.dataSet = dataSet;
204 | }
205 |
206 | @Override public void onDataUpdated(List items, StorageChange change) {
207 | dataSet.removeDataListener(this);
208 | if (!isRemoved && items.isEmpty()) {
209 | isRemoved = true;
210 | resume();
211 | }
212 | }
213 | }
214 |
215 | }
216 |
--------------------------------------------------------------------------------
/droidsnapper/src/androidTest/java/io/techery/snapper/test/benchmark/ProjectionPerformanceTest.java:
--------------------------------------------------------------------------------
1 | package io.techery.snapper.test.benchmark;
2 |
3 | import android.support.test.runner.AndroidJUnit4;
4 |
5 | import org.junit.runner.RunWith;
6 |
7 | import java.util.ArrayList;
8 | import java.util.List;
9 |
10 | import io.techery.snapper.model.User;
11 | import io.techery.snapper.projection.IProjection;
12 |
13 | @RunWith(AndroidJUnit4.class)
14 | public class ProjectionPerformanceTest extends PerformanceTest {
15 |
16 | List projections;
17 | static final int DATA_VIEW_COUNT = 5;
18 |
19 | static final String DATA_LISTENER_LOG_TAG = "Projection";
20 |
21 | @Override public void initStorage() {
22 | super.initStorage();
23 | addProjections(true);
24 | }
25 |
26 | @Override public void release() {
27 | for (IProjection projection : projections) {
28 | projection.close();
29 | }
30 | projections.clear();
31 | super.release();
32 | }
33 |
34 | private void addProjections(final boolean withInitializerListener) {
35 | runWithAwait(DATA_VIEW_COUNT, new Runnable() {
36 | @Override public void run() {
37 | projections = new ArrayList