├── .buildscript └── deploy_snapshot.sh ├── .gitignore ├── .travis.yml ├── CHANGELOG.md ├── LICENSE.txt ├── README.md ├── build.gradle ├── example-app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── dany │ │ └── example │ │ ├── MainActivity.kt │ │ └── data │ │ ├── Bar.kt │ │ ├── DataObject.kt │ │ └── Foo.kt │ └── res │ ├── layout │ └── activity_main.xml │ ├── mipmap-hdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ ├── mipmap-mdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ ├── mipmap-xhdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ ├── mipmap-xxhdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ ├── mipmap-xxxhdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ └── values │ ├── colors.xml │ ├── strings.xml │ └── styles.xml ├── gradle.properties ├── gradle ├── maven-push.gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── kotlincursor-api ├── .gitignore ├── build.gradle ├── gradle.properties └── src │ └── main │ └── java │ └── kotlincursor │ └── annotation │ ├── ColumnAdapter.kt │ ├── ColumnName.kt │ ├── ColumnTypeAdapter.kt │ └── KCursorData.kt ├── kotlincursor-compiler ├── .gitignore ├── build.gradle ├── gradle.properties └── src │ ├── main │ └── java │ │ └── kotlincursor │ │ └── processor │ │ ├── ColumnProperty.kt │ │ ├── KCursorDataClass.kt │ │ └── KCursorDataProcessor.kt │ └── test │ └── java │ ├── android │ ├── content │ │ └── ContentValues.java │ └── database │ │ └── Cursor.java │ └── kotlincursor │ ├── data │ └── DataClasses.kt │ ├── processor │ └── KCursorDataProcessorTest.kt │ └── test │ └── TestMessager.kt └── settings.gradle /.buildscript/deploy_snapshot.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # Deploy a jar, source jar, and javadoc jar to Sonatype's snapshot repo. 4 | # 5 | # Adapted from https://coderwall.com/p/9b_lfq and 6 | # http://benlimmer.com/2013/12/26/automatically-publish-javadoc-to-gh-pages-with-travis-ci/ 7 | 8 | SLUG="danysantiago/kotlin-cursor" 9 | JDK="oraclejdk8" 10 | BRANCH="master" 11 | 12 | set -e 13 | 14 | if [ "$TRAVIS_REPO_SLUG" != "$SLUG" ]; then 15 | echo "Skipping snapshot deployment: wrong repository. Expected '$SLUG' but was '$TRAVIS_REPO_SLUG'." 16 | elif [ "$TRAVIS_JDK_VERSION" != "$JDK" ]; then 17 | echo "Skipping snapshot deployment: wrong JDK. Expected '$JDK' but was '$TRAVIS_JDK_VERSION'." 18 | elif [ "$TRAVIS_PULL_REQUEST" != "false" ]; then 19 | echo "Skipping snapshot deployment: was pull request." 20 | elif [ "$TRAVIS_BRANCH" != "$BRANCH" ]; then 21 | echo "Skipping snapshot deployment: wrong branch. Expected '$BRANCH' but was '$TRAVIS_BRANCH'." 22 | else 23 | echo "Deploying snapshot..." 24 | ./gradlew clean :kotlincursor-api:uploadArchives :kotlincursor-compiler:uploadArchives 25 | echo "Snapshot deployed!" 26 | fi -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/workspace.xml 5 | /.idea/libraries 6 | .DS_Store 7 | /build 8 | /captures 9 | .externalNativeBuild 10 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: android 2 | android: 3 | components: 4 | - tools 5 | - platform-tools 6 | - build-tools-25.0.3 7 | - android-25 8 | 9 | jdk: 10 | - oraclejdk8 11 | 12 | script: 13 | - ./gradlew clean :kotlincursor-compiler:jar :kotlincursor-compiler:test 14 | 15 | after_success: 16 | - .buildscript/deploy_snapshot.sh 17 | 18 | env: 19 | global: 20 | - secure: "GI8QorRX4MtGvojkjmlZm5ruGyr0ZN87dRQuqwQLBlEyraN0Z8wOioCyuszrWWyfxeF+eKjD0wnUFaoy9R65eVRepDWsgD0mC6hiwCYDbOTsaGucYu0vz4YK9/n+4FR7CHAyvCBVyzBf2zwwM/WRMZ5TmV6xkbrAdGGQ19c/QiONyKC3knLJVpnAr4b8n/j9H3QtB4sXL1WNbR00V3yzlQm1nM6ClKbnigIEeCHZIF9qB3CqZaRnxU+36Txf6Fm+6GPynxyQtzXUDMWXIcXzOsCIBzYbL/oukJ+HCYLiaV3ihPgIhBYHEH0OAqIww95cskX1LBd4688pdc8NmrYfhDw4fhUSfdRguT/xrk33/rWD0AoMiMOSSG4rBLa7XC6BB72uP+UqQabQIWF8LQ3zoJh9nRJbS5EG790KsGUFCUtpbNMiEN+jk/07Q0fQ6oTz7L3XKQcN0mcNoQys1VS8p7aRPK/KEAQNuij6uLAkx5PEGP0ueyjAHPsCE5OAjmBo4w7gTeA1BMytVPqUS14wpOjA5BQ7CbN9bGrPxnWQzt6oDeixyeLm8VIGcTgPiv00CuifrdAFMSU13lxObPhRm4PCRSJbI0IW0oUknm1Kxzx3z3XMmgScKraVV13na1GZyTImRkVqAnpKR9K6rVhw0BilTjueaxPUDYKKNYykXmo=" 21 | - secure: "gyvMD/3fpx9KSr9Qi/Bf2UUtFLNAdC8e4TAElUOY/w49JkEuwEXb61mrvw34sm5oGMeDDx13Y7fmzO4jRPjFb8zXbGjUV7RV4NR9Jh8xnnYIqr2haJRogma0TH8WgLHXVQTmYZ+uCmeauEcthgMUjhQNfMnFZxzL5Avto2S4GdnK07tm3EAJo495h7/74bfXTGMfo2ikGZ702wmP6EH84cls7IKcb2oHbEQgAaaX+PZ1+RHp6U88UAxlP5hXTHqpPm9yy8f9D4X/qth2bL2/H7cAOKmxP5+tttBP7+gh9ftGE/qWhBIMmfRUhG6Nj5fzTyI2O+sSXwwYNgS8ds62bzTeRuZDmlgo3oP1iSB5MrIsJ0hVXfr02TALfHYOK28kiktlbU8QDz8omAInGRjiif+9HXgaJHIrTbR60YlyBTNoubEmrFS2tnR+Hxod925p4geUyac13JznGjdHZi1jdnXZfmULi/Fhq6drk/caTYseogEqUtqDr+YU8Z3ImJ7B016sRhPy5Kbd8hvLu8CN9ZnnFZQy/hOidtxL7hHQruiGqIPtrtNCt6Sd33BMFIiJEAXgFWB08MWn2vH0lmndplrkz7+5qm7P+1O4oOT76F+1cC516NndM7ChZHHuZ5gy3snaIHzqK3kC5r28lyZoGTNgcl/PrsPyCRJt0j96hXw=" 22 | 23 | branches: 24 | except: 25 | - gh-pages 26 | 27 | notifications: 28 | email: false 29 | 30 | sudo: false 31 | 32 | cache: 33 | directories: 34 | - $HOME/.gradle -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | Change Log 2 | ========== 3 | 4 | Version 0.1.1 *(2017-06-18)* 5 | ---------------------------- 6 | 7 | Ignore companion object properties. 8 | 9 | 10 | Version 0.1.0 *(2017-06-10)* 11 | ---------------------------- 12 | 13 | Initial release. 14 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Kotlin-Cursor 2 | 3 | An annotation processor that generates extension functions to convert [Kotlin data classes][data-class] 4 | to [ContentValues][content-values] and from [Cursor][cursor]. 5 | 6 | ## Usage 7 | 8 | Annotate your data class with `@KCursorData` 9 | 10 | ```kotlin 11 | @KCursorData 12 | data class Cat(val name: String) 13 | ``` 14 | 15 | then once the class is processed a file will be generated with the following extension functions: 16 | 17 | ```kotlin 18 | fun Cat.toContentValues(): ContentValues { /* ... */ } 19 | fun Cursor.toCat(): Cat { /* ... */ } 20 | ``` 21 | 22 | ## Custom types 23 | 24 | The following types are supported by default: 25 | 26 | * `String` 27 | * `ByteArray` 28 | * `Double` 29 | * `Float` 30 | * `Int` 31 | * `Long` 32 | * `Short` 33 | * `Boolean` 34 | 35 | Kotlin-Cursor also supports types that are also annotated with `@KCursorData`. For exmaple: 36 | ```kotlin 37 | @KCursorData 38 | data class Bed(val owner: Cat) 39 | ``` 40 | 41 | For other types, you need to use the `@ColumnAdapter` annotation and specify a class that implements 42 | `ColumnTypeAdapter`. For example: 43 | 44 | `Person.kt` 45 | 46 | ```kotlin 47 | data class Person( 48 | val name: String, 49 | @ColumnAdapter(CatListAdapter::class) 50 | val cats: List 51 | ) 52 | ``` 53 | 54 | `CatListColumnTypeAdapter.kt`: 55 | 56 | ```kotlin 57 | class CatListAdapter : ColumnTypeAdapter> { 58 | override fun fromCursor(cursor: Cursor, columnName: String): List { 59 | val listOfCats = cursor.getString(cursor.getColumnIndexOrThrow("cat_list")) 60 | return listOfCats.split(',').map { Cat(it) } 61 | } 62 | 63 | override fun toContentValues(values: ContentValues, columnName: String, value: List) { 64 | values.put("cat_list", value.map { it.name }.joinToString(separator = ",")) 65 | } 66 | } 67 | ``` 68 | 69 | ## Setup 70 | 71 | Add a Gradle dependency: 72 | 73 | ```groovy 74 | compile 'com.github.danysantiago:kotlincursor-api:0.1.1' 75 | kapt 'com.github.danysantiago:kotlincursor-compiler:0.1.1' 76 | ``` 77 | Snapshots of the development version are available in [Sonatype's `snapshots` repository][snap]. 78 | 79 | ## Thanks 80 | 81 | To [Gabriel Ittner][gabriel]'s [auto-value-cursor][auto-cursor] for which this project is 82 | based on. 83 | 84 | [content-values]: https://developer.android.com/reference/android/content/ContentValues.html 85 | [cursor]: https://developer.android.com/reference/android/database/Cursor.html 86 | [data-class]: https://kotlinlang.org/docs/reference/data-classes.html 87 | [gabriel]: https://github.com/gabrielittner 88 | [auto-cursor]: https://github.com/gabrielittner/auto-value-cursor 89 | [snap]: https://oss.sonatype.org/content/repositories/snapshots/ 90 | 91 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | ext.kotlin_version = '1.1.2-4' 5 | repositories { 6 | maven { url "https://maven.google.com" } 7 | jcenter() 8 | mavenCentral() 9 | } 10 | dependencies { 11 | classpath 'com.android.tools.build:gradle:3.0.0-alpha4' 12 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" 13 | 14 | // NOTE: Do not place your application dependencies here; they belong 15 | // in the individual module build.gradle files 16 | } 17 | } 18 | 19 | allprojects { 20 | repositories { 21 | maven { url "https://maven.google.com" } 22 | jcenter() 23 | mavenCentral() 24 | } 25 | } 26 | 27 | task clean(type: Delete) { 28 | delete rootProject.buildDir 29 | } -------------------------------------------------------------------------------- /example-app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /example-app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | apply plugin: 'kotlin-android' 3 | apply plugin: 'kotlin-kapt' 4 | 5 | android { 6 | compileSdkVersion 25 7 | buildToolsVersion "25.0.3" 8 | defaultConfig { 9 | applicationId "kotlincursor.example" 10 | minSdkVersion 21 11 | targetSdkVersion 25 12 | versionCode 1 13 | versionName "1.0" 14 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 15 | } 16 | buildTypes { 17 | release { 18 | minifyEnabled false 19 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 20 | } 21 | } 22 | } 23 | 24 | dependencies { 25 | 26 | compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" 27 | 28 | compile "com.android.support:appcompat-v7:25.3.1" 29 | compile "com.android.support.constraint:constraint-layout:1.0.2" 30 | 31 | compile project(":kotlincursor-api") 32 | kapt project(":kotlincursor-compiler") 33 | } 34 | -------------------------------------------------------------------------------- /example-app/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/dsantiagorivera/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 | 19 | # Uncomment this to preserve the line number information for 20 | # debugging stack traces. 21 | #-keepattributes SourceFile,LineNumberTable 22 | 23 | # If you keep the line number information, uncomment this to 24 | # hide the original source file name. 25 | #-renamesourcefileattribute SourceFile 26 | -------------------------------------------------------------------------------- /example-app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /example-app/src/main/java/dany/example/MainActivity.kt: -------------------------------------------------------------------------------- 1 | package dany.example 2 | 3 | import android.os.Bundle 4 | import android.support.v7.app.AppCompatActivity 5 | 6 | class MainActivity : AppCompatActivity() { 7 | 8 | override fun onCreate(savedInstanceState: Bundle?) { 9 | super.onCreate(savedInstanceState) 10 | setContentView(R.layout.activity_main) 11 | } 12 | } -------------------------------------------------------------------------------- /example-app/src/main/java/dany/example/data/Bar.kt: -------------------------------------------------------------------------------- 1 | package dany.example.data 2 | 3 | import kotlincursor.annotation.KCursorData 4 | 5 | @KCursorData 6 | data class Bar( 7 | val someValue: Int 8 | ) 9 | -------------------------------------------------------------------------------- /example-app/src/main/java/dany/example/data/DataObject.kt: -------------------------------------------------------------------------------- 1 | package dany.example.data 2 | 3 | import kotlincursor.annotation.ColumnAdapter 4 | import kotlincursor.annotation.ColumnName 5 | import kotlincursor.annotation.KCursorData 6 | 7 | @KCursorData 8 | data class DataObject( 9 | val aString: String, 10 | 11 | val aNullableString: String?, 12 | 13 | val aByteArray: ByteArray, 14 | 15 | val aNullableByteArray: ByteArray?, 16 | 17 | val aDouble: Double, 18 | 19 | val aNullableDouble: Double?, 20 | 21 | val aFloat: Float, 22 | 23 | val aNullableFloat: Float?, 24 | 25 | val anInt: Int, 26 | 27 | val anNullableInt: Int?, 28 | 29 | val anLong: Long, 30 | 31 | val anNullableLong: Long?, 32 | 33 | val anShort: Short, 34 | 35 | val anNullableShort: Short?, 36 | 37 | val anBoolean: Boolean, 38 | 39 | val anNullableBoolean: Boolean?, 40 | 41 | val aDataCursorProperty: Bar, 42 | 43 | val aNullableDataCursorProperty: Bar?, 44 | 45 | @ColumnAdapter(Foo.ColumnAdapter::class) 46 | val aColumnAdapterProperty: Foo, 47 | 48 | @ColumnAdapter(Foo.ColumnAdapter::class) 49 | val aNullableColumnAdapterProperty: Foo?, 50 | 51 | @ColumnName("my_named_int") 52 | val aColumnNamedInt: Int, 53 | 54 | @ColumnName("my_nullable_named_int") 55 | val aNullableColumnNamedInt: Int?, 56 | 57 | @ColumnName("my_named_cursor_data_class") 58 | val aNamedDataCursorProperty: Bar, 59 | 60 | @ColumnName("my_nullable_named_cursor_data_class") 61 | val aNullableNamedDataCursorProperty: Bar?, 62 | 63 | @ColumnName("my_named_column_adapter") 64 | @ColumnAdapter(Foo.ColumnAdapter::class) 65 | val aNamedColumnAdapterProperty: Foo, 66 | 67 | @ColumnName("my_nullable_named_column_adapter") 68 | @ColumnAdapter(Foo.ColumnAdapter::class) 69 | val aNullableNamedColumnAdapterProperty: Foo? 70 | ) 71 | -------------------------------------------------------------------------------- /example-app/src/main/java/dany/example/data/Foo.kt: -------------------------------------------------------------------------------- 1 | package dany.example.data 2 | 3 | import android.content.ContentValues 4 | import android.database.Cursor 5 | import kotlincursor.annotation.ColumnTypeAdapter 6 | 7 | data class Foo( 8 | val someOther: Int 9 | ) { 10 | class ColumnAdapter : ColumnTypeAdapter { 11 | override fun fromCursor(cursor: Cursor, columnName: String): Foo { 12 | return Foo(cursor.getInt(cursor.getColumnIndexOrThrow("some_other_value"))) 13 | } 14 | 15 | override fun toContentValues(values: ContentValues, columnName: String, value: Foo) { 16 | values.put("some_other_value", value.someOther) 17 | } 18 | 19 | } 20 | } -------------------------------------------------------------------------------- /example-app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /example-app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danysantiago/kotlin-cursor/336aae090dac73c3614cb5eeac9ac7cfb5b2f834/example-app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /example-app/src/main/res/mipmap-hdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danysantiago/kotlin-cursor/336aae090dac73c3614cb5eeac9ac7cfb5b2f834/example-app/src/main/res/mipmap-hdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /example-app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danysantiago/kotlin-cursor/336aae090dac73c3614cb5eeac9ac7cfb5b2f834/example-app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /example-app/src/main/res/mipmap-mdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danysantiago/kotlin-cursor/336aae090dac73c3614cb5eeac9ac7cfb5b2f834/example-app/src/main/res/mipmap-mdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /example-app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danysantiago/kotlin-cursor/336aae090dac73c3614cb5eeac9ac7cfb5b2f834/example-app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /example-app/src/main/res/mipmap-xhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danysantiago/kotlin-cursor/336aae090dac73c3614cb5eeac9ac7cfb5b2f834/example-app/src/main/res/mipmap-xhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /example-app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danysantiago/kotlin-cursor/336aae090dac73c3614cb5eeac9ac7cfb5b2f834/example-app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /example-app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danysantiago/kotlin-cursor/336aae090dac73c3614cb5eeac9ac7cfb5b2f834/example-app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /example-app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danysantiago/kotlin-cursor/336aae090dac73c3614cb5eeac9ac7cfb5b2f834/example-app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /example-app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danysantiago/kotlin-cursor/336aae090dac73c3614cb5eeac9ac7cfb5b2f834/example-app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /example-app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #3F51B5 4 | #303F9F 5 | #FF4081 6 | 7 | -------------------------------------------------------------------------------- /example-app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | My Application 3 | 4 | -------------------------------------------------------------------------------- /example-app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | VERSION_NAME=0.1.2-SNAPSHOT 2 | GROUP=com.github.danysantiago 3 | 4 | POM_DESCRIPTION=Kotlin Cursor & ContentValues boilerplate annotation processor. 5 | 6 | POM_URL=https://github.com/danysantiago/kotlin-cursor 7 | POM_SCM_URL=https://github.com/danysantiago/kotlin-cursor 8 | POM_SCM_CONNECTION=scm:git@github.com:danysantiago/kotlin-cursor.git 9 | POM_SCM_DEV_CONNECTION=scm:git@github.com:danysantiago/kotlin-cursor.git 10 | 11 | POM_LICENCE_NAME=The Apache Software License, Version 2.0 12 | POM_LICENCE_URL=http://www.apache.org/licenses/LICENSE-2.0.txt 13 | POM_LICENCE_DIST=repo 14 | 15 | POM_DEVELOPER_ID=danysantiago 16 | POM_DEVELOPER_NAME=Daniel Santiago 17 | -------------------------------------------------------------------------------- /gradle/maven-push.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013 Chris Banes 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | apply plugin: 'maven' 18 | apply plugin: 'signing' 19 | 20 | version = VERSION_NAME 21 | group = GROUP 22 | 23 | def isReleaseBuild() { 24 | return VERSION_NAME.contains("SNAPSHOT") == false 25 | } 26 | 27 | def getReleaseRepositoryUrl() { 28 | return hasProperty('RELEASE_REPOSITORY_URL') ? RELEASE_REPOSITORY_URL 29 | : "https://oss.sonatype.org/service/local/staging/deploy/maven2/" 30 | } 31 | 32 | def getSnapshotRepositoryUrl() { 33 | return hasProperty('SNAPSHOT_REPOSITORY_URL') ? SNAPSHOT_REPOSITORY_URL 34 | : "https://oss.sonatype.org/content/repositories/snapshots/" 35 | } 36 | 37 | def getRepositoryUsername() { 38 | return hasProperty('SONATYPE_NEXUS_USERNAME') ? SONATYPE_NEXUS_USERNAME : "" 39 | } 40 | 41 | def getRepositoryPassword() { 42 | return hasProperty('SONATYPE_NEXUS_PASSWORD') ? SONATYPE_NEXUS_PASSWORD : "" 43 | } 44 | 45 | afterEvaluate { project -> 46 | uploadArchives { 47 | repositories { 48 | mavenDeployer { 49 | beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) } 50 | 51 | pom.groupId = GROUP 52 | pom.artifactId = POM_ARTIFACT_ID 53 | pom.version = VERSION_NAME 54 | 55 | repository(url: getReleaseRepositoryUrl()) { 56 | authentication(userName: getRepositoryUsername(), password: getRepositoryPassword()) 57 | } 58 | snapshotRepository(url: getSnapshotRepositoryUrl()) { 59 | authentication(userName: getRepositoryUsername(), password: getRepositoryPassword()) 60 | } 61 | 62 | pom.project { 63 | name POM_NAME 64 | packaging POM_PACKAGING 65 | description POM_DESCRIPTION 66 | url POM_URL 67 | 68 | scm { 69 | url POM_SCM_URL 70 | connection POM_SCM_CONNECTION 71 | developerConnection POM_SCM_DEV_CONNECTION 72 | } 73 | 74 | licenses { 75 | license { 76 | name POM_LICENCE_NAME 77 | url POM_LICENCE_URL 78 | distribution POM_LICENCE_DIST 79 | } 80 | } 81 | 82 | developers { 83 | developer { 84 | id POM_DEVELOPER_ID 85 | name POM_DEVELOPER_NAME 86 | } 87 | } 88 | } 89 | } 90 | } 91 | } 92 | 93 | signing { 94 | required { isReleaseBuild() && gradle.taskGraph.hasTask("uploadArchives") } 95 | sign configurations.archives 96 | } 97 | 98 | if (project.getPlugins().hasPlugin('com.android.application') || 99 | project.getPlugins().hasPlugin('com.android.library')) { 100 | task install(type: Upload, dependsOn: assemble) { 101 | repositories.mavenInstaller { 102 | configuration = configurations.archives 103 | 104 | pom.groupId = GROUP 105 | pom.artifactId = POM_ARTIFACT_ID 106 | pom.version = VERSION_NAME 107 | 108 | pom.project { 109 | name POM_NAME 110 | packaging POM_PACKAGING 111 | description POM_DESCRIPTION 112 | url POM_URL 113 | 114 | scm { 115 | url POM_SCM_URL 116 | connection POM_SCM_CONNECTION 117 | developerConnection POM_SCM_DEV_CONNECTION 118 | } 119 | 120 | licenses { 121 | license { 122 | name POM_LICENCE_NAME 123 | url POM_LICENCE_URL 124 | distribution POM_LICENCE_DIST 125 | } 126 | } 127 | 128 | developers { 129 | developer { 130 | id POM_DEVELOPER_ID 131 | name POM_DEVELOPER_NAME 132 | } 133 | } 134 | } 135 | } 136 | } 137 | 138 | task androidJavadocs(type: Javadoc) { 139 | source = android.sourceSets.main.java.source 140 | classpath += project.files(android.getBootClasspath().join(File.pathSeparator)) 141 | } 142 | 143 | task androidJavadocsJar(type: Jar, dependsOn: androidJavadocs) { 144 | classifier = 'javadoc' 145 | from androidJavadocs.destinationDir 146 | } 147 | 148 | task androidSourcesJar(type: Jar) { 149 | classifier = 'sources' 150 | from android.sourceSets.main.java.source 151 | } 152 | } else { 153 | install { 154 | repositories.mavenInstaller { 155 | pom.groupId = GROUP 156 | pom.artifactId = POM_ARTIFACT_ID 157 | pom.version = VERSION_NAME 158 | 159 | pom.project { 160 | name POM_NAME 161 | packaging POM_PACKAGING 162 | description POM_DESCRIPTION 163 | url POM_URL 164 | 165 | scm { 166 | url POM_SCM_URL 167 | connection POM_SCM_CONNECTION 168 | developerConnection POM_SCM_DEV_CONNECTION 169 | } 170 | 171 | licenses { 172 | license { 173 | name POM_LICENCE_NAME 174 | url POM_LICENCE_URL 175 | distribution POM_LICENCE_DIST 176 | } 177 | } 178 | 179 | developers { 180 | developer { 181 | id POM_DEVELOPER_ID 182 | name POM_DEVELOPER_NAME 183 | } 184 | } 185 | } 186 | } 187 | } 188 | 189 | task sourcesJar(type: Jar, dependsOn:classes) { 190 | classifier = 'sources' 191 | from sourceSets.main.allSource 192 | } 193 | 194 | task javadocJar(type: Jar, dependsOn:javadoc) { 195 | classifier = 'javadoc' 196 | from javadoc.destinationDir 197 | } 198 | } 199 | 200 | if (JavaVersion.current().isJava8Compatible()) { 201 | allprojects { 202 | tasks.withType(Javadoc) { 203 | options.addStringOption('Xdoclint:none', '-quiet') 204 | } 205 | } 206 | } 207 | 208 | artifacts { 209 | if (project.getPlugins().hasPlugin('com.android.application') || 210 | project.getPlugins().hasPlugin('com.android.library')) { 211 | archives androidSourcesJar 212 | archives androidJavadocsJar 213 | } else { 214 | archives sourcesJar 215 | archives javadocJar 216 | } 217 | } 218 | } -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danysantiago/kotlin-cursor/336aae090dac73c3614cb5eeac9ac7cfb5b2f834/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Fri Jun 16 22:12:59 PDT 2017 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.0-rc-1-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # Attempt to set APP_HOME 46 | # Resolve links: $0 may be a link 47 | PRG="$0" 48 | # Need this for relative symlinks. 49 | while [ -h "$PRG" ] ; do 50 | ls=`ls -ld "$PRG"` 51 | link=`expr "$ls" : '.*-> \(.*\)$'` 52 | if expr "$link" : '/.*' > /dev/null; then 53 | PRG="$link" 54 | else 55 | PRG=`dirname "$PRG"`"/$link" 56 | fi 57 | done 58 | SAVED="`pwd`" 59 | cd "`dirname \"$PRG\"`/" >/dev/null 60 | APP_HOME="`pwd -P`" 61 | cd "$SAVED" >/dev/null 62 | 63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 64 | 65 | # Determine the Java command to use to start the JVM. 66 | if [ -n "$JAVA_HOME" ] ; then 67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 68 | # IBM's JDK on AIX uses strange locations for the executables 69 | JAVACMD="$JAVA_HOME/jre/sh/java" 70 | else 71 | JAVACMD="$JAVA_HOME/bin/java" 72 | fi 73 | if [ ! -x "$JAVACMD" ] ; then 74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 75 | 76 | Please set the JAVA_HOME variable in your environment to match the 77 | location of your Java installation." 78 | fi 79 | else 80 | JAVACMD="java" 81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 82 | 83 | Please set the JAVA_HOME variable in your environment to match the 84 | location of your Java installation." 85 | fi 86 | 87 | # Increase the maximum file descriptors if we can. 88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 89 | MAX_FD_LIMIT=`ulimit -H -n` 90 | if [ $? -eq 0 ] ; then 91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 92 | MAX_FD="$MAX_FD_LIMIT" 93 | fi 94 | ulimit -n $MAX_FD 95 | if [ $? -ne 0 ] ; then 96 | warn "Could not set maximum file descriptor limit: $MAX_FD" 97 | fi 98 | else 99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 100 | fi 101 | fi 102 | 103 | # For Darwin, add options to specify how the application appears in the dock 104 | if $darwin; then 105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 106 | fi 107 | 108 | # For Cygwin, switch paths to Windows format before running java 109 | if $cygwin ; then 110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 112 | JAVACMD=`cygpath --unix "$JAVACMD"` 113 | 114 | # We build the pattern for arguments to be converted via cygpath 115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 116 | SEP="" 117 | for dir in $ROOTDIRSRAW ; do 118 | ROOTDIRS="$ROOTDIRS$SEP$dir" 119 | SEP="|" 120 | done 121 | OURCYGPATTERN="(^($ROOTDIRS))" 122 | # Add a user-defined pattern to the cygpath arguments 123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 125 | fi 126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 127 | i=0 128 | for arg in "$@" ; do 129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 131 | 132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 134 | else 135 | eval `echo args$i`="\"$arg\"" 136 | fi 137 | i=$((i+1)) 138 | done 139 | case $i in 140 | (0) set -- ;; 141 | (1) set -- "$args0" ;; 142 | (2) set -- "$args0" "$args1" ;; 143 | (3) set -- "$args0" "$args1" "$args2" ;; 144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 150 | esac 151 | fi 152 | 153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 154 | function splitJvmOpts() { 155 | JVM_OPTS=("$@") 156 | } 157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 159 | 160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 161 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /kotlincursor-api/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /kotlincursor-api/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'kotlin' 2 | 3 | dependencies { 4 | compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" 5 | compileOnly "com.google.android:android:4.1.1.4" 6 | } 7 | 8 | apply from: rootProject.file('gradle/maven-push.gradle') -------------------------------------------------------------------------------- /kotlincursor-api/gradle.properties: -------------------------------------------------------------------------------- 1 | POM_NAME=Kotlin Cursor API 2 | POM_ARTIFACT_ID=kotlincursor-api 3 | POM_PACKAGING=jar -------------------------------------------------------------------------------- /kotlincursor-api/src/main/java/kotlincursor/annotation/ColumnAdapter.kt: -------------------------------------------------------------------------------- 1 | package kotlincursor.annotation 2 | 3 | import kotlin.reflect.KClass 4 | 5 | /** 6 | * Annotation that indicates the [ColumnTypeAdapter] to use when converting the annotated field to 7 | * [android.content.ContentValues] and from [android.database.Cursor]. 8 | */ 9 | @Target(AnnotationTarget.FIELD) 10 | annotation class ColumnAdapter(val value: KClass>) -------------------------------------------------------------------------------- /kotlincursor-api/src/main/java/kotlincursor/annotation/ColumnName.kt: -------------------------------------------------------------------------------- 1 | package kotlincursor.annotation 2 | 3 | /** 4 | * Annotation that indicates that a different name is to be used when converting the annotated field 5 | * to [android.content.ContentValues] and from [android.database.Cursor]. 6 | */ 7 | @Target(AnnotationTarget.FIELD) 8 | annotation class ColumnName(val value: String) -------------------------------------------------------------------------------- /kotlincursor-api/src/main/java/kotlincursor/annotation/ColumnTypeAdapter.kt: -------------------------------------------------------------------------------- 1 | package kotlincursor.annotation 2 | 3 | import android.content.ContentValues 4 | import android.database.Cursor 5 | 6 | interface ColumnTypeAdapter { 7 | fun fromCursor(cursor: Cursor, columnName: String): T 8 | fun toContentValues(values: ContentValues, columnName: String, value: T) 9 | } -------------------------------------------------------------------------------- /kotlincursor-api/src/main/java/kotlincursor/annotation/KCursorData.kt: -------------------------------------------------------------------------------- 1 | package kotlincursor.annotation 2 | 3 | /** 4 | * Annotation that indicates that a class can be converted to [android.content.ContentValues] and 5 | * from [android.database.Cursor]. 6 | * 7 | * For example, annotating a data class as follows: 8 | * 9 | * ``` 10 | * @KCursorData 11 | * data class Cat(name: String) 12 | * ``` 13 | * 14 | * will generate a Kotlin file containing extension functions for performing the conversion. 15 | * 16 | * ``` 17 | * fun Cat.toContentValues(): ContentValues { 18 | * val values = android.content.ContentValues() 19 | * values.put("name", name) 20 | * return values 21 | * } 22 | * 23 | * fun Cursor.toCat(): Cat { 24 | * val name = this.getInt(this.getColumnIndexOrThrow("name")) 25 | * return Cat(name) 26 | * } 27 | * ``` 28 | */ 29 | @Target(AnnotationTarget.CLASS) 30 | annotation class KCursorData -------------------------------------------------------------------------------- /kotlincursor-compiler/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /kotlincursor-compiler/build.gradle: -------------------------------------------------------------------------------- 1 | import org.gradle.internal.jvm.Jvm 2 | 3 | apply plugin: 'kotlin' 4 | 5 | dependencies { 6 | compile project(":kotlincursor-api") 7 | 8 | compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" 9 | compile "com.google.auto.service:auto-service:1.0-rc2" 10 | kapt "com.google.auto.service:auto-service:1.0-rc2" 11 | compile "com.squareup:kotlinpoet:0.2.0" 12 | 13 | testCompile "junit:junit:4.12" 14 | testCompile "com.google.testing.compile:compile-testing:0.11" 15 | testCompile "com.google.truth:truth:0.33" 16 | testCompile "com.google.guava:guava:22.0" 17 | testCompile files(Jvm.current().getToolsJar()) 18 | } 19 | 20 | apply from: rootProject.file('gradle/maven-push.gradle') -------------------------------------------------------------------------------- /kotlincursor-compiler/gradle.properties: -------------------------------------------------------------------------------- 1 | POM_NAME=Kotlin Cursor Compiler 2 | POM_ARTIFACT_ID=kotlincursor-compiler 3 | POM_PACKAGING=jar -------------------------------------------------------------------------------- /kotlincursor-compiler/src/main/java/kotlincursor/processor/ColumnProperty.kt: -------------------------------------------------------------------------------- 1 | package kotlincursor.processor 2 | 3 | import com.squareup.kotlinpoet.BOOLEAN 4 | import com.squareup.kotlinpoet.ClassName 5 | import com.squareup.kotlinpoet.DOUBLE 6 | import com.squareup.kotlinpoet.FLOAT 7 | import com.squareup.kotlinpoet.INT 8 | import com.squareup.kotlinpoet.LONG 9 | import com.squareup.kotlinpoet.SHORT 10 | import com.squareup.kotlinpoet.TypeName 11 | import kotlincursor.annotation.ColumnAdapter 12 | import kotlincursor.annotation.ColumnName 13 | import kotlincursor.annotation.KCursorData 14 | import javax.lang.model.element.Element 15 | import javax.lang.model.element.VariableElement 16 | import javax.lang.model.type.TypeMirror 17 | import javax.lang.model.util.Types 18 | import kotlin.reflect.KClass 19 | 20 | 21 | class ColumnProperty( 22 | element: VariableElement 23 | ) { 24 | val element: VariableElement = element 25 | val humanName: String = element.simpleName.toString() 26 | val columnName: String by lazy(this::initColumnName) 27 | val columnType: TypeName = TypeName.get(element.asType()) 28 | val columnAdapter: ClassName? by lazy(this::initColumnAdapter) 29 | val isPrimitive: Boolean = element.asType().kind.isPrimitive 30 | val isNullable: Boolean by lazy(this::initIsNullable) 31 | val isSupportedType: Boolean = SUPPORTED_TYPES.contains(columnType) 32 | 33 | private fun initColumnName(): String { 34 | val value = getAnnotationValue(element, ColumnName::class, "value") 35 | return if (value != null && value is String) value else humanName 36 | } 37 | 38 | private fun initColumnAdapter(): ClassName? { 39 | val value = getAnnotationValue(element, ColumnAdapter::class, "value") 40 | return if (value != null && value is TypeMirror) TypeName.get(value) as ClassName else null 41 | } 42 | 43 | private fun getAnnotationValue(element: Element, annotation: KClass, key: String): Any? { 44 | return element.annotationMirrors 45 | .find { it.annotationType.toString() == annotation.java.canonicalName } 46 | ?.elementValues?.entries?.find { it.key.simpleName.contentEquals(key) } 47 | ?.value?.value 48 | } 49 | 50 | private fun initIsNullable(): Boolean { 51 | return !isPrimitive && element.annotationMirrors 52 | .map { it.annotationType.asElement().simpleName.toString() } 53 | .none { it == kotlincursor.processor.ColumnProperty.NON_NULL_ANNOTATION_NAME 54 | || it == kotlincursor.processor.ColumnProperty.NOT_NULL_ANNOTATION_NAME } 55 | } 56 | 57 | fun isColumnTypeCursorDataClass(typeUtils: Types): Boolean { 58 | return typeUtils.asElement(element.asType()).annotationMirrors 59 | .map { it.annotationType.toString() } 60 | .contains(KCursorData::class.java.canonicalName) 61 | } 62 | 63 | fun getCursorMethod(): String { 64 | if (!isSupportedType) { 65 | throw IllegalStateException("Called cursorMethod but Column is not a supported type") 66 | } 67 | 68 | when(columnType) { 69 | TypeName.get(String::class) -> return "this.getString(%L)" 70 | TypeName.get(ByteArray::class) -> return "this.getBlob(%L)" 71 | DOUBLE, TypeName.get(java.lang.Double::class) -> return "this.getDouble(%L)" 72 | FLOAT, TypeName.get(java.lang.Float::class) -> return "this.getFloat(%L)" 73 | INT, TypeName.get(java.lang.Integer::class) -> return "this.getInt(%L)" 74 | LONG, TypeName.get(java.lang.Long::class) -> return "this.getLong(%L)" 75 | SHORT, TypeName.get(java.lang.Short::class) -> return "this.getShort(%L)" 76 | BOOLEAN, TypeName.get(java.lang.Boolean::class) -> return "this.getInt(%L) == 1" 77 | else -> throw IllegalStateException("isSupportedType is true but type $columnType wasn't handled") 78 | } 79 | } 80 | 81 | companion object { 82 | const val NON_NULL_ANNOTATION_NAME = "NonNull" 83 | const val NOT_NULL_ANNOTATION_NAME = "NotNull" 84 | 85 | internal val SUPPORTED_TYPES = arrayOf( 86 | TypeName.get(String::class), 87 | TypeName.get(ByteArray::class), 88 | DOUBLE, TypeName.get(java.lang.Double::class), 89 | FLOAT, TypeName.get(java.lang.Float::class), 90 | INT, TypeName.get(java.lang.Integer::class), 91 | LONG, TypeName.get(java.lang.Long::class), 92 | SHORT, TypeName.get(java.lang.Short::class), 93 | BOOLEAN, TypeName.get(java.lang.Boolean::class) 94 | ) 95 | } 96 | } -------------------------------------------------------------------------------- /kotlincursor-compiler/src/main/java/kotlincursor/processor/KCursorDataClass.kt: -------------------------------------------------------------------------------- 1 | package kotlincursor.processor 2 | 3 | import com.squareup.kotlinpoet.ClassName 4 | import com.squareup.kotlinpoet.CodeBlock 5 | import com.squareup.kotlinpoet.FunSpec 6 | import com.squareup.kotlinpoet.KotlinFile 7 | import com.squareup.kotlinpoet.TypeName 8 | import javax.annotation.processing.Messager 9 | import javax.lang.model.element.ElementKind 10 | import javax.lang.model.element.Modifier 11 | import javax.lang.model.element.TypeElement 12 | import javax.lang.model.element.VariableElement 13 | import javax.lang.model.util.Elements 14 | import javax.lang.model.util.Types 15 | import javax.tools.Diagnostic 16 | 17 | class KCursorDataClass( 18 | val messager: Messager, 19 | val elements: Elements, 20 | val types: Types 21 | 22 | ) { 23 | fun generateKotlinFile(classElement: TypeElement): KotlinFile { 24 | val packageName = elements.getPackageOf(classElement).qualifiedName.toString() 25 | val fileName = CLASS_FILE_PREFIX + classElement.simpleName.toString() 26 | 27 | val properties = classElement.enclosedElements 28 | .filter { it.kind == ElementKind.FIELD 29 | && !it.modifiers.contains(Modifier.STATIC) 30 | && it is VariableElement } 31 | .map { ColumnProperty(it as VariableElement) } 32 | 33 | return KotlinFile.builder(packageName, fileName) 34 | .addFun(generateToContentValuesMethod(classElement, properties)) 35 | .addFun(generateFromCursorMethod(classElement, properties)) 36 | .build() 37 | } 38 | 39 | private fun generateToContentValuesMethod(classElement: TypeElement, properties: List): FunSpec { 40 | val methodBuilder = FunSpec.builder("toContentValues") 41 | .receiver(TypeName.get(classElement.asType())) 42 | .addStatement("val values = $CONTENT_VALUES()") 43 | .returns(CONTENT_VALUES) 44 | 45 | properties.forEach { 46 | val columnAdapter = it.columnAdapter 47 | if (columnAdapter != null) { 48 | if (it.isNullable) methodBuilder.addCode("if (${it.humanName} != null) ") 49 | methodBuilder.addStatement( 50 | "%L().toContentValues(values, \"${it.columnName}\", ${it.humanName})", 51 | columnAdapter) 52 | } else if (it.isSupportedType) { 53 | methodBuilder.addStatement( 54 | "values.put(\"${it.columnName}\", ${it.humanName})") 55 | } else if (it.isColumnTypeCursorDataClass(types)) { 56 | if (it.isNullable) methodBuilder.addCode("if (${it.humanName} != null) ") 57 | methodBuilder.addStatement( 58 | "values.putAll(${it.humanName}.toContentValues())") 59 | } else { 60 | messager.printMessage(Diagnostic.Kind.ERROR, "Property \"${it.humanName}\" " + 61 | "of type ${it.columnType} can't be converted to ContentValues.", 62 | it.element) 63 | } 64 | } 65 | return methodBuilder.addStatement("return values").build() 66 | } 67 | 68 | private fun generateFromCursorMethod(classElement: TypeElement, properties: List): FunSpec { 69 | val methodBuilder = FunSpec.builder("to${classElement.simpleName}") 70 | .receiver(CURSOR) 71 | .returns(TypeName.get(classElement.asType())) 72 | 73 | val names = properties.map { it.humanName } 74 | properties.forEach { 75 | val columnAdapter = it.columnAdapter 76 | if (columnAdapter != null) { 77 | methodBuilder.addStatement( 78 | "val ${it.humanName} = %L().fromCursor(this, \"${it.columnName}\")", 79 | columnAdapter) 80 | } else if (it.isSupportedType) { 81 | if (it.isNullable) { 82 | methodBuilder.addCode(generateReadNullableProperty(it)) 83 | } else { 84 | methodBuilder.addCode(generateReadProperty(it)) 85 | } 86 | } else if (it.isColumnTypeCursorDataClass(types)) { 87 | val columnTypeSimpleName = types.asElement(it.element.asType()).simpleName 88 | methodBuilder.addStatement( 89 | "val ${it.humanName} = this.to$columnTypeSimpleName()" 90 | ) 91 | } else { 92 | messager.printMessage(Diagnostic.Kind.ERROR, "Property \"${it.humanName}\" " + 93 | "of type ${it.columnType} can't be converted from Cursor.", 94 | it.element) 95 | } 96 | } 97 | val constructorCallBlock = generateClassConstructorCall(classElement.simpleName.toString(), names) 98 | return methodBuilder.addStatement("return $constructorCallBlock").build() 99 | } 100 | 101 | private fun generateReadNullableProperty(property: ColumnProperty): CodeBlock { 102 | val columnIndexVariableName = "${property.humanName}Index" 103 | val getValueBlock = CodeBlock.of(property.getCursorMethod(), columnIndexVariableName) 104 | val nullCheckBlock = CodeBlock.of( 105 | "if ($columnIndexVariableName == -1 || this.isNull($columnIndexVariableName)) null else %L", 106 | getValueBlock) 107 | return CodeBlock.builder() 108 | .addStatement("val $columnIndexVariableName = this.getColumnIndex(\"${property.columnName}\")") 109 | .addStatement("val ${property.humanName} = %L", nullCheckBlock) 110 | .build() 111 | } 112 | 113 | private fun generateReadProperty(property: ColumnProperty): CodeBlock { 114 | val getColumnIndexOrThrowBlock = CodeBlock.of("this.getColumnIndexOrThrow(\"${property.columnName}\")") 115 | val getValueBlock = CodeBlock.of(property.getCursorMethod(), getColumnIndexOrThrowBlock) 116 | return CodeBlock.builder() 117 | .addStatement("val ${property.humanName} = %L", getValueBlock) 118 | .build() 119 | } 120 | 121 | private fun generateClassConstructorCall(className: String, names: List): String { 122 | return "$className(${names.joinToString()})" 123 | } 124 | 125 | companion object { 126 | const val CLASS_FILE_PREFIX = "KCursor" 127 | 128 | val CONTENT_VALUES = ClassName.get("android.content", "ContentValues") 129 | val CURSOR = ClassName.get("android.database", "Cursor") 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /kotlincursor-compiler/src/main/java/kotlincursor/processor/KCursorDataProcessor.kt: -------------------------------------------------------------------------------- 1 | package kotlincursor.processor 2 | 3 | import com.google.auto.service.AutoService 4 | import kotlincursor.annotation.KCursorData 5 | import javax.annotation.processing.AbstractProcessor 6 | import javax.annotation.processing.Filer 7 | import javax.annotation.processing.Messager 8 | import javax.annotation.processing.ProcessingEnvironment 9 | import javax.annotation.processing.Processor 10 | import javax.annotation.processing.RoundEnvironment 11 | import javax.lang.model.SourceVersion 12 | import javax.lang.model.element.TypeElement 13 | import javax.lang.model.util.Elements 14 | import javax.lang.model.util.Types 15 | import javax.tools.Diagnostic 16 | import javax.tools.StandardLocation 17 | 18 | 19 | @AutoService(Processor::class) 20 | class KCursorDataProcessor : AbstractProcessor() { 21 | 22 | val messager: Messager by lazy { processingEnv.messager } 23 | val elements: Elements by lazy { processingEnv.elementUtils } 24 | val types: Types by lazy { processingEnv.typeUtils } 25 | val filer: Filer by lazy { processingEnv.filer } 26 | 27 | override fun init(processingEnv: ProcessingEnvironment) { 28 | super.init(processingEnv) 29 | 30 | messager.printMessage(Diagnostic.Kind.OTHER, "Initialized KotlinCursorProcessor") 31 | } 32 | 33 | override fun getSupportedAnnotationTypes() = setOf(KCursorData::class.java.canonicalName) 34 | 35 | override fun getSupportedSourceVersion() = SourceVersion.RELEASE_8 36 | 37 | override fun process(annotations: MutableSet, roundEnv: RoundEnvironment): Boolean { 38 | val cursorDataClass = KCursorDataClass(messager, elements, types) 39 | 40 | roundEnv.getElementsAnnotatedWith(KCursorData::class.java).forEach { 41 | if (it is TypeElement) { 42 | val kotlinFile = cursorDataClass.generateKotlinFile(it) 43 | val file = filer.createResource(StandardLocation.SOURCE_OUTPUT, 44 | kotlinFile.packageName, "${kotlinFile.fileName}.kt", it) 45 | file.openWriter().use { 46 | kotlinFile.writeTo(it) 47 | } 48 | } else { 49 | messager.printMessage(Diagnostic.Kind.WARNING, "Found element annotated with " + 50 | "${KCursorData::class} but its not a data class!", it) 51 | } 52 | } 53 | 54 | return true 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /kotlincursor-compiler/src/test/java/android/content/ContentValues.java: -------------------------------------------------------------------------------- 1 | package android.content; 2 | 3 | public class ContentValues { 4 | public void put(String key, int value) {} 5 | } 6 | -------------------------------------------------------------------------------- /kotlincursor-compiler/src/test/java/android/database/Cursor.java: -------------------------------------------------------------------------------- 1 | package android.database; 2 | 3 | public interface Cursor { 4 | int getInt(int columnIndex); 5 | int getColumnIndexOrThrow(String columnName) throws IllegalArgumentException; 6 | } 7 | -------------------------------------------------------------------------------- /kotlincursor-compiler/src/test/java/kotlincursor/data/DataClasses.kt: -------------------------------------------------------------------------------- 1 | package kotlincursor.data 2 | 3 | import android.content.ContentValues 4 | import android.database.Cursor 5 | import kotlincursor.annotation.ColumnAdapter 6 | import kotlincursor.annotation.ColumnName 7 | import kotlincursor.annotation.ColumnTypeAdapter 8 | import kotlincursor.annotation.KCursorData 9 | 10 | @KCursorData 11 | data class SimpleData(val a: Int) { 12 | class ColumnAdapter : ColumnTypeAdapter { 13 | override fun fromCursor(cursor: Cursor, columnName: String): SimpleData { 14 | return SimpleData(cursor.getInt(cursor.getColumnIndexOrThrow(columnName))) 15 | } 16 | 17 | override fun toContentValues(values: ContentValues, columnName: String, value: SimpleData) { 18 | values.put(columnName, value.a) 19 | } 20 | } 21 | } 22 | 23 | @KCursorData 24 | data class SimpleNamedData(@ColumnName("my_name") val a: Int) 25 | 26 | @KCursorData 27 | data class SupportedTypesData( 28 | val aString: String, 29 | val aByteArray: ByteArray, 30 | val aDouble: Double, 31 | val aFloat: Float, 32 | val anInt: Int, 33 | val anLong: Long, 34 | val anShort: Short, 35 | val anBoolean: Boolean 36 | ) 37 | 38 | @KCursorData 39 | data class NullableSupportedTypesData( 40 | val aString: String?, 41 | val aByteArray: ByteArray?, 42 | val aDouble: Double?, 43 | val aFloat: Float?, 44 | val anInt: Int?, 45 | val anLong: Long?, 46 | val anShort: Short?, 47 | val anBoolean: Boolean? 48 | ) 49 | 50 | @KCursorData 51 | data class NestedCursorData(val a: SimpleData) 52 | 53 | @KCursorData 54 | data class NullableNestedCursorData(val a: SimpleData?) 55 | 56 | @KCursorData 57 | data class AdapterData(@ColumnAdapter(SimpleData.ColumnAdapter::class) val a: SimpleData) 58 | 59 | @KCursorData 60 | data class NullableAdapterData(@ColumnAdapter(SimpleData.ColumnAdapter::class) val a: SimpleData?) 61 | 62 | @KCursorData 63 | data class InvalidData(val invalidProperty: List) 64 | 65 | @KCursorData 66 | data class AccompaniedData(val a: Int) { 67 | companion object { 68 | @JvmStatic val TAG = "AccompaniedData" 69 | } 70 | } -------------------------------------------------------------------------------- /kotlincursor-compiler/src/test/java/kotlincursor/processor/KCursorDataProcessorTest.kt: -------------------------------------------------------------------------------- 1 | package kotlincursor.processor 2 | 3 | import com.google.common.truth.Truth.assertThat 4 | import com.google.testing.compile.CompilationRule 5 | import kotlincursor.data.AccompaniedData 6 | import kotlincursor.data.AdapterData 7 | import kotlincursor.data.InvalidData 8 | import kotlincursor.data.NestedCursorData 9 | import kotlincursor.data.NullableAdapterData 10 | import kotlincursor.data.NullableNestedCursorData 11 | import kotlincursor.data.NullableSupportedTypesData 12 | import kotlincursor.data.SimpleData 13 | import kotlincursor.data.SimpleNamedData 14 | import kotlincursor.data.SupportedTypesData 15 | import kotlincursor.test.TestMessager 16 | import org.junit.Assert.fail 17 | import org.junit.Before 18 | import org.junit.Rule 19 | import org.junit.Test 20 | import javax.annotation.processing.Messager 21 | import javax.lang.model.util.Elements 22 | import javax.lang.model.util.Types 23 | import kotlin.properties.Delegates 24 | 25 | 26 | class KCursorDataProcessorTest { 27 | 28 | @get:Rule val rule = CompilationRule() 29 | 30 | var elements by Delegates.notNull() 31 | var types by Delegates.notNull() 32 | var messager by Delegates.notNull() 33 | 34 | @Before 35 | fun setup() { 36 | elements = rule.elements 37 | types = rule.types 38 | messager = TestMessager() 39 | } 40 | 41 | @Test 42 | fun simple() { 43 | val expected = """ 44 | |package kotlincursor.data 45 | | 46 | |import android.content.ContentValues 47 | |import android.database.Cursor 48 | | 49 | |fun SimpleData.toContentValues(): ContentValues { 50 | | val values = android.content.ContentValues() 51 | | values.put("a", a) 52 | | return values 53 | |} 54 | | 55 | |fun Cursor.toSimpleData(): SimpleData { 56 | | val a = this.getInt(this.getColumnIndexOrThrow("a")) 57 | | return SimpleData(a) 58 | |} 59 | |""".trimMargin() 60 | 61 | val actual = KCursorDataClass(messager, elements, types).generateKotlinFile( 62 | elements.getTypeElement(SimpleData::class.java.canonicalName)) 63 | 64 | assertThat(actual.toString()).isEqualTo(expected) 65 | } 66 | 67 | @Test 68 | fun columnName() { 69 | val expected = """ 70 | |package kotlincursor.data 71 | | 72 | |import android.content.ContentValues 73 | |import android.database.Cursor 74 | | 75 | |fun SimpleNamedData.toContentValues(): ContentValues { 76 | | val values = android.content.ContentValues() 77 | | values.put("my_name", a) 78 | | return values 79 | |} 80 | | 81 | |fun Cursor.toSimpleNamedData(): SimpleNamedData { 82 | | val a = this.getInt(this.getColumnIndexOrThrow("my_name")) 83 | | return SimpleNamedData(a) 84 | |} 85 | |""".trimMargin() 86 | 87 | val actual = KCursorDataClass(messager, elements, types).generateKotlinFile( 88 | elements.getTypeElement(SimpleNamedData::class.java.canonicalName)) 89 | 90 | assertThat(actual.toString()).isEqualTo(expected) 91 | } 92 | 93 | @Test 94 | fun supportedTypes() { 95 | val expected = """ 96 | |package kotlincursor.data 97 | | 98 | |import android.content.ContentValues 99 | |import android.database.Cursor 100 | | 101 | |fun SupportedTypesData.toContentValues(): ContentValues { 102 | | val values = android.content.ContentValues() 103 | | values.put("aString", aString) 104 | | values.put("aByteArray", aByteArray) 105 | | values.put("aDouble", aDouble) 106 | | values.put("aFloat", aFloat) 107 | | values.put("anInt", anInt) 108 | | values.put("anLong", anLong) 109 | | values.put("anShort", anShort) 110 | | values.put("anBoolean", anBoolean) 111 | | return values 112 | |} 113 | | 114 | |fun Cursor.toSupportedTypesData(): SupportedTypesData { 115 | | val aString = this.getString(this.getColumnIndexOrThrow("aString")) 116 | | val aByteArray = this.getBlob(this.getColumnIndexOrThrow("aByteArray")) 117 | | val aDouble = this.getDouble(this.getColumnIndexOrThrow("aDouble")) 118 | | val aFloat = this.getFloat(this.getColumnIndexOrThrow("aFloat")) 119 | | val anInt = this.getInt(this.getColumnIndexOrThrow("anInt")) 120 | | val anLong = this.getLong(this.getColumnIndexOrThrow("anLong")) 121 | | val anShort = this.getShort(this.getColumnIndexOrThrow("anShort")) 122 | | val anBoolean = this.getInt(this.getColumnIndexOrThrow("anBoolean")) == 1 123 | | return SupportedTypesData(aString, aByteArray, aDouble, aFloat, anInt, anLong, anShort, anBoolean) 124 | |} 125 | |""".trimMargin() 126 | 127 | val actual = KCursorDataClass(messager, elements, types).generateKotlinFile( 128 | elements.getTypeElement(SupportedTypesData::class.java.canonicalName)) 129 | 130 | assertThat(actual.toString()).isEqualTo(expected) 131 | } 132 | 133 | @Test 134 | fun nullableSupportedTypes() { 135 | val expected = """ 136 | |package kotlincursor.data 137 | | 138 | |import android.content.ContentValues 139 | |import android.database.Cursor 140 | | 141 | |fun NullableSupportedTypesData.toContentValues(): ContentValues { 142 | | val values = android.content.ContentValues() 143 | | values.put("aString", aString) 144 | | values.put("aByteArray", aByteArray) 145 | | values.put("aDouble", aDouble) 146 | | values.put("aFloat", aFloat) 147 | | values.put("anInt", anInt) 148 | | values.put("anLong", anLong) 149 | | values.put("anShort", anShort) 150 | | values.put("anBoolean", anBoolean) 151 | | return values 152 | |} 153 | | 154 | |fun Cursor.toNullableSupportedTypesData(): NullableSupportedTypesData { 155 | | val aStringIndex = this.getColumnIndex("aString") 156 | | val aString = if (aStringIndex == -1 || this.isNull(aStringIndex)) null else this.getString(aStringIndex) 157 | | val aByteArrayIndex = this.getColumnIndex("aByteArray") 158 | | val aByteArray = if (aByteArrayIndex == -1 || this.isNull(aByteArrayIndex)) null else this.getBlob(aByteArrayIndex) 159 | | val aDoubleIndex = this.getColumnIndex("aDouble") 160 | | val aDouble = if (aDoubleIndex == -1 || this.isNull(aDoubleIndex)) null else this.getDouble(aDoubleIndex) 161 | | val aFloatIndex = this.getColumnIndex("aFloat") 162 | | val aFloat = if (aFloatIndex == -1 || this.isNull(aFloatIndex)) null else this.getFloat(aFloatIndex) 163 | | val anIntIndex = this.getColumnIndex("anInt") 164 | | val anInt = if (anIntIndex == -1 || this.isNull(anIntIndex)) null else this.getInt(anIntIndex) 165 | | val anLongIndex = this.getColumnIndex("anLong") 166 | | val anLong = if (anLongIndex == -1 || this.isNull(anLongIndex)) null else this.getLong(anLongIndex) 167 | | val anShortIndex = this.getColumnIndex("anShort") 168 | | val anShort = if (anShortIndex == -1 || this.isNull(anShortIndex)) null else this.getShort(anShortIndex) 169 | | val anBooleanIndex = this.getColumnIndex("anBoolean") 170 | | val anBoolean = if (anBooleanIndex == -1 || this.isNull(anBooleanIndex)) null else this.getInt(anBooleanIndex) == 1 171 | | return NullableSupportedTypesData(aString, aByteArray, aDouble, aFloat, anInt, anLong, anShort, anBoolean) 172 | |} 173 | |""".trimMargin() 174 | 175 | val actual = KCursorDataClass(messager, elements, types).generateKotlinFile( 176 | elements.getTypeElement(NullableSupportedTypesData::class.java.canonicalName)) 177 | 178 | assertThat(actual.toString()).isEqualTo(expected) 179 | } 180 | 181 | @Test 182 | fun nestedKCursorData() { 183 | val expected = """ 184 | |package kotlincursor.data 185 | | 186 | |import android.content.ContentValues 187 | |import android.database.Cursor 188 | | 189 | |fun NestedCursorData.toContentValues(): ContentValues { 190 | | val values = android.content.ContentValues() 191 | | values.putAll(a.toContentValues()) 192 | | return values 193 | |} 194 | | 195 | |fun Cursor.toNestedCursorData(): NestedCursorData { 196 | | val a = this.toSimpleData() 197 | | return NestedCursorData(a) 198 | |} 199 | |""".trimMargin() 200 | 201 | val actual = KCursorDataClass(messager, elements, types).generateKotlinFile( 202 | elements.getTypeElement(NestedCursorData::class.java.canonicalName)) 203 | 204 | assertThat(actual.toString()).isEqualTo(expected) 205 | } 206 | 207 | @Test 208 | fun nullableNestedKCursorData() { 209 | val expected = """ 210 | |package kotlincursor.data 211 | | 212 | |import android.content.ContentValues 213 | |import android.database.Cursor 214 | | 215 | |fun NullableNestedCursorData.toContentValues(): ContentValues { 216 | | val values = android.content.ContentValues() 217 | | if (a != null) values.putAll(a.toContentValues()) 218 | | return values 219 | |} 220 | | 221 | |fun Cursor.toNullableNestedCursorData(): NullableNestedCursorData { 222 | | val a = this.toSimpleData() 223 | | return NullableNestedCursorData(a) 224 | |} 225 | |""".trimMargin() 226 | 227 | val actual = KCursorDataClass(messager, elements, types).generateKotlinFile( 228 | elements.getTypeElement(NullableNestedCursorData::class.java.canonicalName)) 229 | 230 | assertThat(actual.toString()).isEqualTo(expected) 231 | } 232 | 233 | @Test 234 | fun columnAdapter() { 235 | val expected = """ 236 | |package kotlincursor.data 237 | | 238 | |import android.content.ContentValues 239 | |import android.database.Cursor 240 | | 241 | |fun AdapterData.toContentValues(): ContentValues { 242 | | val values = android.content.ContentValues() 243 | | kotlincursor.data.SimpleData.ColumnAdapter().toContentValues(values, "a", a) 244 | | return values 245 | |} 246 | | 247 | |fun Cursor.toAdapterData(): AdapterData { 248 | | val a = kotlincursor.data.SimpleData.ColumnAdapter().fromCursor(this, "a") 249 | | return AdapterData(a) 250 | |} 251 | |""".trimMargin() 252 | 253 | val actual = KCursorDataClass(messager, elements, types).generateKotlinFile( 254 | elements.getTypeElement(AdapterData::class.java.canonicalName)) 255 | 256 | assertThat(actual.toString()).isEqualTo(expected) 257 | } 258 | 259 | @Test 260 | fun nullableColumnAdapter() { 261 | val expected = """ 262 | |package kotlincursor.data 263 | | 264 | |import android.content.ContentValues 265 | |import android.database.Cursor 266 | | 267 | |fun NullableAdapterData.toContentValues(): ContentValues { 268 | | val values = android.content.ContentValues() 269 | | if (a != null) kotlincursor.data.SimpleData.ColumnAdapter().toContentValues(values, "a", a) 270 | | return values 271 | |} 272 | | 273 | |fun Cursor.toNullableAdapterData(): NullableAdapterData { 274 | | val a = kotlincursor.data.SimpleData.ColumnAdapter().fromCursor(this, "a") 275 | | return NullableAdapterData(a) 276 | |} 277 | |""".trimMargin() 278 | 279 | val actual = KCursorDataClass(messager, elements, types).generateKotlinFile( 280 | elements.getTypeElement(NullableAdapterData::class.java.canonicalName)) 281 | 282 | assertThat(actual.toString()).isEqualTo(expected) 283 | } 284 | 285 | @Test 286 | fun invalidProperty() { 287 | val classElement = elements.getTypeElement(InvalidData::class.java.canonicalName) 288 | try { 289 | KCursorDataClass(messager, elements, types).generateKotlinFile(classElement) 290 | fail("Generating a Kotlin Class for $classElement should have thrown an exception.") 291 | } catch (e: TestMessager.ErrorMsgException) { 292 | assertThat(e.element!!.simpleName.toString()).isEqualTo("invalidProperty") 293 | } 294 | } 295 | 296 | @Test 297 | fun companionObject() { 298 | val expected = """ 299 | |package kotlincursor.data 300 | | 301 | |import android.content.ContentValues 302 | |import android.database.Cursor 303 | | 304 | |fun AccompaniedData.toContentValues(): ContentValues { 305 | | val values = android.content.ContentValues() 306 | | values.put("a", a) 307 | | return values 308 | |} 309 | | 310 | |fun Cursor.toAccompaniedData(): AccompaniedData { 311 | | val a = this.getInt(this.getColumnIndexOrThrow("a")) 312 | | return AccompaniedData(a) 313 | |} 314 | |""".trimMargin() 315 | 316 | val actual = KCursorDataClass(messager, elements, types).generateKotlinFile( 317 | elements.getTypeElement(AccompaniedData::class.java.canonicalName)) 318 | 319 | assertThat(actual.toString()).isEqualTo(expected) 320 | } 321 | } -------------------------------------------------------------------------------- /kotlincursor-compiler/src/test/java/kotlincursor/test/TestMessager.kt: -------------------------------------------------------------------------------- 1 | package kotlincursor.test 2 | 3 | import javax.annotation.processing.Messager 4 | import javax.lang.model.element.AnnotationMirror 5 | import javax.lang.model.element.AnnotationValue 6 | import javax.lang.model.element.Element 7 | import javax.tools.Diagnostic 8 | 9 | 10 | class TestMessager : Messager { 11 | 12 | override fun printMessage(kind: Diagnostic.Kind, msg: CharSequence) { 13 | printMessage(kind, msg, null) 14 | } 15 | 16 | override fun printMessage(kind: Diagnostic.Kind, msg: CharSequence, e: Element?) { 17 | printMessage(kind, msg, e, null) 18 | } 19 | 20 | override fun printMessage(kind: Diagnostic.Kind, msg: CharSequence, e: Element?, a: AnnotationMirror?) { 21 | printMessage(kind, msg, e, a, null) 22 | } 23 | 24 | override fun printMessage(kind: Diagnostic.Kind, msg: CharSequence, e: Element?, a: AnnotationMirror?, v: AnnotationValue?) { 25 | if (kind == Diagnostic.Kind.ERROR) { 26 | throw ErrorMsgException(msg.toString(), e) 27 | } else { 28 | System.out.println(msg) 29 | } 30 | } 31 | 32 | class ErrorMsgException(msg: String, val element: Element?) : RuntimeException(msg) 33 | } 34 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':example-app', ':kotlincursor-api', ':kotlincursor-compiler' 2 | --------------------------------------------------------------------------------