├── ormgap-example ├── src │ └── main │ │ ├── res │ │ ├── values │ │ │ ├── styles.xml │ │ │ ├── dimens.xml │ │ │ └── strings.xml │ │ ├── drawable-hdpi │ │ │ └── ic_launcher.png │ │ ├── drawable-mdpi │ │ │ └── ic_launcher.png │ │ ├── drawable-xhdpi │ │ │ └── ic_launcher.png │ │ ├── drawable-xxhdpi │ │ │ └── ic_launcher.png │ │ ├── menu │ │ │ └── main.xml │ │ ├── values-w820dp │ │ │ └── dimens.xml │ │ └── layout │ │ │ └── activity_main.xml │ │ ├── AndroidManifest.xml │ │ └── java │ │ └── com │ │ └── example │ │ └── ormgap │ │ ├── MainActivity.java │ │ ├── SimpleData.java │ │ └── DatabaseHelper.java ├── proguard.txt └── build.gradle ├── ormgap-plugin ├── gradle.properties ├── src │ └── main │ │ ├── resources │ │ └── META-INF │ │ │ └── gradle-plugins │ │ │ ├── ormgap.properties │ │ │ └── com.github.stephanenicolas.ormgap.properties │ │ ├── groovy │ │ └── com │ │ │ └── github │ │ │ └── stephanenicolas │ │ │ └── ormgap │ │ │ ├── ORMGAPPluginExtension.groovy │ │ │ └── ORMGAPPlugin.groovy │ │ └── java │ │ └── com │ │ └── github │ │ └── stephanenicolas │ │ └── ormgap │ │ ├── CreateOrmLiteConfigAction.java │ │ └── CreateOrmLiteConfigTask.java └── build.gradle ├── settings.gradle ├── gradle ├── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties └── gradle-mvn-push.gradle ├── ormgap-ormlite-extension ├── gradle.properties ├── build.gradle └── src │ └── main │ └── java │ └── com │ └── github │ └── stephanenicolas │ └── ormgap │ └── OrmLiteConfigUtil.java ├── .gitignore ├── .travis.yml ├── RELEASING.md ├── gradle.properties ├── CHANGELOG.md ├── gradlew.bat ├── README.md ├── gradlew └── LICENSE /ormgap-example/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /ormgap-plugin/gradle.properties: -------------------------------------------------------------------------------- 1 | POM_ARTIFACT_ID=ormgap-plugin 2 | POM_NAME="ORM LITE Android Gradle plugin" -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':ormgap-plugin' 2 | include ':ormgap-ormlite-extension' 3 | //include ':ormgap-example' 4 | 5 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stephanenicolas/ormlite-android-gradle-plugin/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /ormgap-ormlite-extension/gradle.properties: -------------------------------------------------------------------------------- 1 | POM_ARTIFACT_ID=ormgap-ormlite-extension 2 | POM_NAME="ORM LITE Android Gradle plugin ORMLite Extension" -------------------------------------------------------------------------------- /ormgap-plugin/src/main/resources/META-INF/gradle-plugins/ormgap.properties: -------------------------------------------------------------------------------- 1 | implementation-class=com.github.stephanenicolas.ormgap.ORMGAPPlugin 2 | -------------------------------------------------------------------------------- /ormgap-plugin/src/main/resources/META-INF/gradle-plugins/com.github.stephanenicolas.ormgap.properties: -------------------------------------------------------------------------------- 1 | implementation-class=com.github.stephanenicolas.ormgap.ORMGAPPlugin 2 | -------------------------------------------------------------------------------- /ormgap-example/src/main/res/drawable-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stephanenicolas/ormlite-android-gradle-plugin/HEAD/ormgap-example/src/main/res/drawable-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /ormgap-example/src/main/res/drawable-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stephanenicolas/ormlite-android-gradle-plugin/HEAD/ormgap-example/src/main/res/drawable-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /ormgap-example/src/main/res/drawable-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stephanenicolas/ormlite-android-gradle-plugin/HEAD/ormgap-example/src/main/res/drawable-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /ormgap-example/src/main/res/drawable-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stephanenicolas/ormlite-android-gradle-plugin/HEAD/ormgap-example/src/main/res/drawable-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /ormgap-plugin/src/main/groovy/com/github/stephanenicolas/ormgap/ORMGAPPluginExtension.groovy: -------------------------------------------------------------------------------- 1 | package com.github.stephanenicolas.ormgap 2 | 3 | class ORMGAPPluginExtension { 4 | String configFileName = "ormlite_config.txt" 5 | } 6 | -------------------------------------------------------------------------------- /ormgap-example/proguard.txt: -------------------------------------------------------------------------------- 1 | -dontobfuscate 2 | -dontoptimize 3 | -dontpreverify 4 | -verbose 5 | -ignorewarnings 6 | -dontskipnonpubliclibraryclasses 7 | -dontskipnonpubliclibraryclassmembers 8 | 9 | -keepattributes *Annotation* 10 | -------------------------------------------------------------------------------- /ormgap-example/src/main/res/values/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 16dp 4 | 16dp 5 | 6 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Thu Jan 19 09:00:07 PST 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.10.3-all.zip 7 | -------------------------------------------------------------------------------- /ormgap-example/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ORMGAP Example 5 | Hello world! 6 | Settings 7 | 8 | 9 | -------------------------------------------------------------------------------- /ormgap-ormlite-extension/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'java-library' 2 | 3 | dependencies { 4 | implementation 'com.j256.ormlite:ormlite-android:4.48' 5 | } 6 | 7 | javadoc { 8 | failOnError = false 9 | } 10 | 11 | apply from: rootProject.file('gradle/gradle-mvn-push.gradle') 12 | -------------------------------------------------------------------------------- /ormgap-example/src/main/res/menu/main.xml: -------------------------------------------------------------------------------- 1 | 4 | 7 | 8 | -------------------------------------------------------------------------------- /ormgap-example/src/main/res/values-w820dp/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 64dp 6 | 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Built application files 2 | *.apk 3 | *.ap_ 4 | 5 | # Files for the Dalvik VM 6 | *.dex 7 | 8 | # Java class files 9 | *.class 10 | 11 | # Generated files 12 | bin/ 13 | gen/ 14 | 15 | # Gradle files 16 | .gradle/ 17 | build/ 18 | /*/build/ 19 | 20 | # Local configuration file (sdk path, etc) 21 | local.properties 22 | 23 | # Proguard folder generated by Eclipse 24 | proguard/ 25 | 26 | # Log Files 27 | *.log 28 | 29 | #Android Studio/Intelli J 30 | .idea/ 31 | *.iml 32 | 33 | #ORMGAP 34 | ormlite_config.txt 35 | build.properties 36 | -------------------------------------------------------------------------------- /ormgap-example/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 9 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: android 2 | 3 | android: 4 | components: 5 | # https://github.com/travis-ci/travis-ci/issues/5036 6 | - tools 7 | - build-tools-28.0.3 8 | - android-28 9 | - extra-android-m2repository 10 | 11 | jdk: 12 | - openjdk8 13 | 14 | install: 15 | # Without TERM=dumb, we get mangled output in the Travis console 16 | - TERM=dumb ./gradlew clean assemble 17 | 18 | script: 19 | - TERM=dumb ./gradlew check 20 | 21 | env: 22 | global: 23 | - TERM=dumb 24 | 25 | notifications: 26 | email: false 27 | 28 | #from http://blog.ansuz.nl/index.php/2014/06/01/robolectric-and-cobertura-with-gradle/ 29 | after_success: 30 | - ./gradlew clean cobertura coveralls -d 31 | -------------------------------------------------------------------------------- /ormgap-example/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 10 | 11 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /RELEASING.md: -------------------------------------------------------------------------------- 1 | Releasing 2 | ======== 3 | 4 | 1. Change TWICE the version in `gradle.properties` to a non-SNAPSHOT version. 5 | 2. Update the `CHANGELOG.md` for the impending release. 6 | 3. Update the `README.md` with the new version (if it applies). 7 | 4. `git commit -am "Prepare for release X.Y.Z."` (where X.Y.Z is the new version) 8 | 5. `./gradlew --no-build-cache clean uploadArchives` 9 | 6. Visit [Sonatype Nexus](https://oss.sonatype.org/) and promote the artifact. 10 | 7. `git tag -a X.Y.X -m "Version X.Y.Z"` (where X.Y.Z is the new version) 11 | 8. Update TWICE the `gradle.properties` to the next SNAPSHOT version. 12 | 9. `git commit -am "Prepare next development version."` 13 | 10. `git push && git push --tags` 14 | 15 | If step 5 or 6 fails, drop the Sonatype repo, fix the problem, commit, and start again at step 5. 16 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | version=3.0.6-SNAPSHOT 2 | GROUP=com.github.stephanenicolas.ormgap 3 | VERSION_NAME=3.0.6-SNAPSHOT 4 | 5 | POM_PACKAGING=JAR 6 | POM_DESCRIPTION=A Gradle plugin for Android to generate an ORMLite configuration file and boost DAOs creations. 7 | POM_URL=https://github.com/stephannicolas/ormlite-android-gradle-plugin/ 8 | POM_SCM_URL=https://github.com/stephannicolas/ormlite-android-gradle-plugin/ 9 | POM_SCM_CONNECTION=scm:git@github.com/stephannicolas/ormlite-android-gradle-plugin.git 10 | POM_SCM_DEV_CONNECTION=scm:git@github.com:stephannicolas/ormlite-android-gradle-plugin.git 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 | POM_DEVELOPER_ID=SNI 15 | POM_DEVELOPER_NAME=Stéphane NICOLAS 16 | 17 | ORMLITE_VERSION=4.48 18 | -------------------------------------------------------------------------------- /ormgap-example/build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | repositories { 3 | google() 4 | jcenter() 5 | 6 | // NOTE: This is only needed when developing the plugin! 7 | mavenLocal() 8 | } 9 | 10 | dependencies { 11 | classpath 'com.android.tools.build:gradle:3.3.0' 12 | classpath 'com.github.stephanenicolas.ormgap:ormgap-plugin:3.0.5-SNAPSHOT' 13 | } 14 | } 15 | 16 | apply plugin: 'android' 17 | apply plugin: 'ormgap' 18 | 19 | 20 | repositories { 21 | google() 22 | jcenter() 23 | 24 | // NOTE: This is only needed when developing the plugin! 25 | mavenLocal() 26 | } 27 | 28 | dependencies { 29 | compile 'com.j256.ormlite:ormlite-android:4.48' 30 | } 31 | 32 | android { 33 | compileSdkVersion 28 34 | buildToolsVersion '28.0.3' 35 | 36 | compileOptions { 37 | sourceCompatibility JavaVersion.VERSION_1_7 38 | targetCompatibility JavaVersion.VERSION_1_7 39 | } 40 | buildTypes { 41 | debug { 42 | minifyEnabled true 43 | proguardFile 'proguard.txt' 44 | } 45 | } 46 | } 47 | 48 | ormgap {} 49 | -------------------------------------------------------------------------------- /ormgap-plugin/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'groovy' 2 | apply plugin: 'java-library' 3 | 4 | repositories { 5 | google() 6 | jcenter() 7 | mavenLocal() 8 | } 9 | 10 | dependencies { 11 | project (':ormgap-ormlite-extension') 12 | implementation gradleApi() 13 | implementation localGroovy() 14 | implementation 'com.android.tools.build:gradle:3.3.0' 15 | implementation("com.j256.ormlite:ormlite-android:$ORMLITE_VERSION") 16 | } 17 | 18 | logging.captureStandardOutput LogLevel.INFO 19 | 20 | project.afterEvaluate { 21 | tasks.getByName('compileJava').doFirst { 22 | //we create a file in the plugin project containing the urrent project version 23 | //it will be used later by the plugin to add the proper version of 24 | //dependencies to the project that uses the plugin 25 | def prop = new Properties() 26 | def propFile = new File("${project.rootDir}/ormgap-plugin/src/main/resources/build.properties") 27 | prop.setProperty("com.github.stephanenicolas.ormgap.version", "$version") 28 | propFile.createNewFile(); 29 | prop.store(propFile.newWriter(), null); 30 | } 31 | } 32 | 33 | apply from: rootProject.file('gradle/gradle-mvn-push.gradle') 34 | -------------------------------------------------------------------------------- /ormgap-example/src/main/java/com/example/ormgap/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.example.ormgap; 2 | 3 | import android.app.Activity; 4 | import android.os.Bundle; 5 | import android.view.Menu; 6 | import android.view.MenuItem; 7 | 8 | public class MainActivity extends Activity { 9 | 10 | @Override 11 | protected void onCreate(Bundle savedInstanceState) { 12 | super.onCreate(savedInstanceState); 13 | setContentView(R.layout.activity_main); 14 | } 15 | 16 | 17 | @Override 18 | public boolean onCreateOptionsMenu(Menu menu) { 19 | // Inflate the menu; this adds items to the action bar if it is present. 20 | getMenuInflater().inflate(R.menu.main, menu); 21 | return true; 22 | } 23 | 24 | @Override 25 | public boolean onOptionsItemSelected(MenuItem item) { 26 | // Handle action bar item clicks here. The action bar will 27 | // automatically handle clicks on the Home/Up button, so long 28 | // as you specify a parent activity in AndroidManifest.xml. 29 | int id = item.getItemId(); 30 | if (id == R.id.action_settings) { 31 | return true; 32 | } 33 | return super.onOptionsItemSelected(item); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ### version 3.0.6 (TBR) 2 | 3 | ### version 3.0.5 (February 2nd, 2019) 4 | 5 | * Solve issue 27. Support Task Configuration Avoidance 6 | 7 | ### version 3.0.4 (Jan. 22snd 2018) 8 | 9 | * fix a small warning during the build related to scanning of source directories 10 | 11 | ### version 3.0.3 (Oct. 7th 2017) 12 | 13 | * fix issue 20: https://github.com/stephanenicolas/ormlite-android-gradle-plugin/issues/20 14 | ORM GAP now works with gradle 4.2.1 15 | 16 | ### version 3.0.2 (skipped) 17 | 18 | ### version 3.0.1 (September 30th 2017) 19 | 20 | * fix issue 18: https://github.com/stephanenicolas/ormlite-android-gradle-plugin/issues/18 21 | * fix issue 16: https://github.com/stephanenicolas/ormlite-android-gradle-plugin/issues/16 22 | ORM GAP now adds the extension as `compileOnly` 23 | 24 | ### version 3.0.0 (September 29th 2017) 25 | 26 | * fix issue 14: https://github.com/stephanenicolas/ormlite-android-gradle-plugin/issues/14 27 | ORM GAP is now incremental and cacheable and uses gradle 4.1 28 | 29 | ### version 2.00 (July 6th 2017) 30 | 31 | * fix issue 10: https://github.com/stephanenicolas/ormlite-android-gradle-plugin/issues/10 32 | * fix issue 9: https://github.com/stephanenicolas/ormlite-android-gradle-plugin/issues/9 33 | 34 | the ormlite_config filename can be customized via the plugin extension 35 | the file is now generated in the asset folder and this makes it much smoother w.r.t to Android build cycle. Before we were using the resources but we needed the classes to be generatd which was creating a cycle (classes need resources to be compiled). This is now solved. 36 | 37 | 38 | -------------------------------------------------------------------------------- /ormgap-example/src/main/java/com/example/ormgap/SimpleData.java: -------------------------------------------------------------------------------- 1 | package com.example.ormgap; 2 | 3 | import com.j256.ormlite.field.DatabaseField; 4 | import java.text.SimpleDateFormat; 5 | import java.util.Date; 6 | import java.util.Locale; 7 | 8 | /** 9 | * A simple demonstration object we are creating and persisting to the database. 10 | * from https://github.com/j256/ormlite-examples/blob/master/android/HelloAndroid/src/com/example/helloandroid/SimpleData.java 11 | */ 12 | public class SimpleData { 13 | 14 | // id is generated by the database and set on the object automagically 15 | @DatabaseField(generatedId = true) 16 | int id; 17 | 18 | @DatabaseField(index = true) 19 | String string; 20 | 21 | @DatabaseField 22 | long millis; 23 | 24 | @DatabaseField 25 | Date date; 26 | 27 | @DatabaseField 28 | boolean even; 29 | 30 | @SuppressWarnings("unused") SimpleData() { 31 | } 32 | 33 | public SimpleData(long millis) { 34 | this.date = new Date(millis); 35 | this.string = (millis % 1000) + "ms"; 36 | this.millis = millis; 37 | this.even = ((millis % 2) == 0); 38 | } 39 | 40 | @Override 41 | public String toString() { 42 | StringBuilder sb = new StringBuilder(); 43 | sb.append("id=").append(id); 44 | sb.append(", ").append("str=").append(string); 45 | sb.append(", ").append("ms=").append(millis); 46 | SimpleDateFormat dateFormatter = new SimpleDateFormat("MM/dd HH:mm:ss", Locale.US); 47 | sb.append(", ").append("date=").append(dateFormatter.format(date)); 48 | sb.append(", ").append("even=").append(even); 49 | return sb.toString(); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /ormgap-plugin/src/main/java/com/github/stephanenicolas/ormgap/CreateOrmLiteConfigAction.java: -------------------------------------------------------------------------------- 1 | package com.github.stephanenicolas.ormgap; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | import org.gradle.api.logging.Logger; 6 | 7 | /** 8 | * Create the ORM Lite config file. 9 | * Allows to fully test the task. 10 | * 11 | * @author SNI. 12 | */ 13 | public class CreateOrmLiteConfigAction { 14 | private final File configFile; 15 | private File searchDir; 16 | private String classpath; 17 | private Logger logger; 18 | 19 | public CreateOrmLiteConfigAction(File configFile, 20 | File searchDir, 21 | String classpath, 22 | Logger logger) { 23 | this.configFile = configFile; 24 | this.searchDir = searchDir; 25 | this.classpath = classpath; 26 | this.logger = logger; 27 | } 28 | 29 | public void execute() throws IOException, InterruptedException { 30 | ProcessBuilder builder 31 | = new ProcessBuilder("java", 32 | "-cp", 33 | classpath, 34 | "com.github.stephanenicolas.ormgap.OrmLiteConfigUtil", 35 | configFile.getAbsolutePath(), 36 | searchDir.getAbsolutePath()); 37 | 38 | logger.debug("Generating ORMLite Config file using command line: " + builder.command()); 39 | builder 40 | .inheritIO() 41 | .directory(searchDir); 42 | final int result = builder.start().waitFor(); 43 | if (result != 0) { 44 | throw new RuntimeException("OrmLiteConfigUtil finished with code: " + result); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ORM Lite Android Gradle Plugin [![Build Status](https://travis-ci.org/stephanenicolas/ormlite-android-gradle-plugin.svg?branch=master)](https://travis-ci.org/stephanenicolas/ormlite-android-gradle-plugin)[![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.github.stephanenicolas.ormgap/ormgap-plugin/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.github.stephanenicolas.ormgap/ormgap-plugin) 2 | -------- 3 | 4 | A Gradle plugin for Android to generate an ORMLite configuration file and boost DAOs creations. 5 | 6 | As of version 1.0.13, ORM GAP is fully incremental and gets executed only when classes using ormlite change. 7 | 8 | ### Usage 9 | 10 | ```gradle 11 | //build.gradle 12 | 13 | buildscript { 14 | repositories { 15 | ... 16 | mavenCentral() 17 | } 18 | 19 | dependencies { 20 | ... 21 | classpath 'com.github.stephanenicolas.ormgap:ormgap-plugin:x.y.z' 22 | } 23 | } 24 | 25 | apply plugin: 'android' 26 | apply plugin: 'ormgap' 27 | ... 28 | 29 | ``` 30 | 31 | You will then need to create your database using the ORMLite config file that will be generated during your build (note : you first need to boostrap the system, get a file generated, then reference it.) 32 | 33 | ```java 34 | public DatabaseHelper(Context context) { 35 | super(context, DATABASE_NAME, null, DATABASE_VERSION, R.raw.ormlite_config); 36 | } 37 | ``` 38 | 39 | If you use DAOs : you will need to use the second contructor of ORMLite's DAO class : 40 | ```java 41 | public MyDao(ConnectionSource connectionSource, DatabaseTableConfig tableConfig) 42 | throws SQLException { 43 | super(connectionSource, tableConfig); 44 | } 45 | ``` 46 | 47 | You're all set. 48 | See [ORM Lite docs](http://ormlite.com/javadoc/ormlite-core/doc-files/ormlite.html#Top) for further instructions. 49 | 50 | 51 | ### Example 52 | 53 | An example can be found [in the GH repo](https://github.com/stephanenicolas/ormlite-android-gradle-plugin/tree/master/ormgap-example). 54 | 55 | ### How does it work ? 56 | 57 | We basically just automated a technique that is considered the [best practice for ORM Lite on Android](http://ormlite.com/javadoc/ormlite-core/doc-files/ormlite_4.html#Config-Optimization) : it uses a configuration file, genereated at build time, so that ORMLite doesn't scan annotations. 58 | 59 | ORMGAP will do the following to your build : 60 | * create a task for each variant to generate the ORMLite configuration file (this is customizable, TODO explain the plugin extension). 61 | * we also add a provided dependency to your build that contains our forked utility class. This should disappear in a close future, as soon as we submit a PR to ORM Lite and a new version is released... TODO : submit a PR with ORMLiteConfigUtil changes. 62 | 63 | ### Benchmarking 64 | 65 | Our plan is to make a benchmarking app using the example android app. 66 | 67 | For now, we can only give you a number from our experience at Groupon: the average gain, for all devices of our 50 million users is 10 ms per DAO creation. It might not seem much, but for large apps, it makes a difference. In our app, we gained 400 ms with ORMGAP. 68 | 69 | ### CI 70 | 71 | Travis is almost ready at : https://travis-ci.org/stephanenicolas/ormlite-android-gradle-plugin 72 | 73 | ### Credits 74 | 75 | ORMGAP has been possible thanks to [Groupon](http://groupon.com) ! 76 | 77 | Groupon logo 78 | 79 | And, yes, [we are hiring Android coders](https://jobs.groupon.com/careers/engineering/). 80 | 81 | ORMGAP is part of [our open source effort](https://github.com/groupon). 82 | 83 | License 84 | ------- 85 | 86 | Copyright (C) 2015 Stéphane NICOLAS 87 | 88 | Licensed under the Apache License, Version 2.0 (the "License"); 89 | you may not use this file except in compliance with the License. 90 | You may obtain a copy of the License at 91 | 92 | http://www.apache.org/licenses/LICENSE-2.0 93 | 94 | Unless required by applicable law or agreed to in writing, software 95 | distributed under the License is distributed on an "AS IS" BASIS, 96 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 97 | See the License for the specific language governing permissions and 98 | limitations under the License. 99 | -------------------------------------------------------------------------------- /ormgap-example/src/main/java/com/example/ormgap/DatabaseHelper.java: -------------------------------------------------------------------------------- 1 | package com.example.ormgap; 2 | 3 | import android.content.Context; 4 | import android.database.sqlite.SQLiteDatabase; 5 | import android.util.Log; 6 | import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper; 7 | import com.j256.ormlite.dao.Dao; 8 | import com.j256.ormlite.dao.RuntimeExceptionDao; 9 | import com.j256.ormlite.support.ConnectionSource; 10 | import com.j256.ormlite.table.TableUtils; 11 | import java.sql.SQLException; 12 | 13 | /** 14 | * Database helper class used to manage the creation and upgrading of your database. This class also usually provides 15 | * the DAOs used by the other classes. 16 | * from https://github.com/j256/ormlite-examples/blob/master/android/HelloAndroid/src/com/example/helloandroid/DatabaseHelper.java 17 | */ 18 | public class DatabaseHelper extends OrmLiteSqliteOpenHelper { 19 | 20 | // name of the database file for your application -- change to something appropriate for your app 21 | private static final String DATABASE_NAME = "helloAndroid.db"; 22 | // any time you make changes to your database objects, you may have to increase the database version 23 | private static final int DATABASE_VERSION = 1; 24 | 25 | // the DAO object we use to access the SimpleData table 26 | private Dao simpleDao = null; 27 | private RuntimeExceptionDao simpleRuntimeDao = null; 28 | 29 | public DatabaseHelper(Context context) { 30 | super(context, DATABASE_NAME, null, DATABASE_VERSION, R.raw.ormlite_config); 31 | } 32 | 33 | /** 34 | * This is called when the database is first created. Usually you should call createTable statements here to create 35 | * the tables that will store your data. 36 | */ 37 | @Override 38 | public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) { 39 | try { 40 | Log.i(DatabaseHelper.class.getName(), "onCreate"); 41 | TableUtils.createTable(connectionSource, SimpleData.class); 42 | } catch (SQLException e) { 43 | Log.e(DatabaseHelper.class.getName(), "Can't create database", e); 44 | throw new RuntimeException(e); 45 | } 46 | 47 | // here we try inserting data in the on-create as a test 48 | RuntimeExceptionDao dao = getSimpleDataDao(); 49 | long millis = System.currentTimeMillis(); 50 | // create some entries in the onCreate 51 | SimpleData simple = new SimpleData(millis); 52 | dao.create(simple); 53 | simple = new SimpleData(millis + 1); 54 | dao.create(simple); 55 | Log.i(DatabaseHelper.class.getName(), "created new entries in onCreate: " + millis); 56 | } 57 | 58 | /** 59 | * This is called when your application is upgraded and it has a higher version number. This allows you to adjust 60 | * the various data to match the new version number. 61 | */ 62 | @Override 63 | public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) { 64 | try { 65 | Log.i(DatabaseHelper.class.getName(), "onUpgrade"); 66 | TableUtils.dropTable(connectionSource, SimpleData.class, true); 67 | // after we drop the old databases, we create the new ones 68 | onCreate(db, connectionSource); 69 | } catch (SQLException e) { 70 | Log.e(DatabaseHelper.class.getName(), "Can't drop databases", e); 71 | throw new RuntimeException(e); 72 | } 73 | } 74 | 75 | /** 76 | * Returns the Database Access Object (DAO) for our SimpleData class. It will create it or just give the cached 77 | * value. 78 | */ 79 | public Dao getDao() throws SQLException { 80 | if (simpleDao == null) { 81 | simpleDao = getDao(SimpleData.class); 82 | } 83 | return simpleDao; 84 | } 85 | 86 | /** 87 | * Returns the RuntimeExceptionDao (Database Access Object) version of a Dao for our SimpleData class. It will 88 | * create it or just give the cached value. RuntimeExceptionDao only through RuntimeExceptions. 89 | */ 90 | public RuntimeExceptionDao getSimpleDataDao() { 91 | if (simpleRuntimeDao == null) { 92 | simpleRuntimeDao = getRuntimeExceptionDao(SimpleData.class); 93 | } 94 | return simpleRuntimeDao; 95 | } 96 | 97 | /** 98 | * Close the database connections and clear any cached DAOs. 99 | */ 100 | @Override 101 | public void close() { 102 | super.close(); 103 | simpleDao = null; 104 | simpleRuntimeDao = null; 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /ormgap-plugin/src/main/groovy/com/github/stephanenicolas/ormgap/ORMGAPPlugin.groovy: -------------------------------------------------------------------------------- 1 | package com.github.stephanenicolas.ormgap 2 | 3 | import com.android.build.gradle.AppPlugin 4 | import com.android.build.gradle.LibraryPlugin 5 | import com.android.build.gradle.api.ApplicationVariant 6 | import com.android.build.gradle.api.LibraryVariant 7 | import org.gradle.api.Plugin 8 | import org.gradle.api.Project 9 | import org.gradle.api.file.FileCollection 10 | import org.gradle.api.plugins.PluginCollection 11 | import org.gradle.api.tasks.compile.JavaCompile 12 | import org.gradle.api.tasks.TaskProvider 13 | 14 | /** 15 | * ORM LITE ANDROID PLUGIN 16 | * It will: 17 | *
    18 | *
  • add a task to create the configuration file for ORM LITE 19 | *
  • insert it into the build task graph of your android project 20 | *
  • let you configure the name of the configuration file ? 21 | *
  • work for libraries ? 22 | *
  • work for tests ? 23 | *
*/ 24 | public class ORMGAPPlugin implements Plugin { 25 | @Override 26 | public void apply(Project project) { 27 | def hasApp = project.plugins.withType(AppPlugin) 28 | def hasLib = project.plugins.withType(LibraryPlugin) 29 | ensureProjectIsAndroidAppOrLib(hasApp, hasLib) 30 | 31 | def extension = getExtension() 32 | def pluginExtension = getPluginExtension() 33 | if (extension && pluginExtension) { 34 | project.extensions.create(extension, pluginExtension) 35 | } 36 | 37 | final def log = project.logger 38 | final String LOG_TAG = "ORMGAP" 39 | 40 | final def variants 41 | if (hasApp) { 42 | variants = project.android.applicationVariants 43 | } else { 44 | variants = project.android.libraryVariants 45 | } 46 | 47 | configure(project) 48 | 49 | variants.all { variant -> 50 | log.debug("In variant '${variant.name}'.") 51 | 52 | String variantName 53 | if (variant instanceof ApplicationVariant){ 54 | variantName = ((ApplicationVariant) variant).productFlavors[0]?.name 55 | } else if (variant instanceof LibraryVariant){ 56 | variantName = ((LibraryVariant) variant).mergedFlavor.name 57 | } 58 | 59 | // Use default buildvariant 60 | if(variantName == null || "".equals(variantName)){ 61 | variantName = "main" 62 | } 63 | 64 | def createConfigFileTaskName = "createORMLiteConfigFile${variant.name.capitalize()}" 65 | def createConfigFileTask = project.tasks.register(createConfigFileTaskName, CreateOrmLiteConfigTask) { 66 | description = "Create an ORM Lite configuration file" 67 | 68 | 69 | TaskProvider javaCompile = variant.getJavaCompileProvider() 70 | 71 | FileCollection classpathFileCollection = project.files(project.android.bootClasspath) 72 | classpathFileCollection += javaCompile.get().classpath 73 | classpathFileCollection += project.files(javaCompile.get().destinationDir) 74 | 75 | def path = project.android.sourceSets[variantName].java.srcDirs[0].canonicalPath 76 | if (new File(path).exists()) { 77 | setSources(path) 78 | } else { 79 | setSources(project.android.sourceSets["main"].java.srcDirs[0].canonicalPath) 80 | } 81 | 82 | path = project.android.sourceSets[variantName].assets.srcDirs[0].canonicalPath 83 | setDestDirFolder(path) 84 | setClasspath(classpathFileCollection) 85 | into(project.ormgap.configFileName) 86 | } 87 | createConfigFileTask.configure { dependsOn javaCompile } 88 | 89 | variant.mergeAssetsProvider.configure { dependsOn createConfigFileTask } 90 | 91 | log.debug("ORMLite config file creation task installed after mergeAssets task.") 92 | if (!hasLib) { 93 | variant.installProvider?.configure { dependsOn createConfigFileTask } 94 | } 95 | log.debug("Done with variant '${variant.name}'.") 96 | } 97 | log.debug("Done.") 98 | } 99 | 100 | protected void ensureProjectIsAndroidAppOrLib(PluginCollection hasApp, 101 | PluginCollection hasLib) { 102 | if (!hasApp && !hasLib) { 103 | throw new IllegalStateException("'android' or 'android-library' plugin required.") 104 | } 105 | } 106 | 107 | /** 108 | * Hook to configure the project under build. 109 | * Can be used to add other extensions, plugins, etc. 110 | * @param project the project under build. 111 | */ 112 | protected void configure(Project project) { 113 | //we use the file build.properties that contains the version of 114 | //the extension to use. This avoids all problems related to using version x.y.+ 115 | Properties properties = new Properties() 116 | properties.load(getClass().getClassLoader().getResourceAsStream("build.properties")) 117 | project.dependencies { 118 | compileOnly 'com.github.stephanenicolas.ormgap:ormgap-ormlite-extension:' + properties.get("com.github.stephanenicolas.ormgap.version") 119 | } 120 | } 121 | 122 | /** 123 | * @return the name of the class of the plugin extension associated to the project's extension. 124 | * Can be null, then no extension is created. 125 | * @see #getExtension() 126 | */ 127 | private Class getPluginExtension() { 128 | ORMGAPPluginExtension 129 | } 130 | 131 | /** 132 | * @return the extension of the project that this plugin can create. 133 | * It will be associated to the plugin extension. 134 | * Can be null, then no extension is created. 135 | * @see #getPluginExtension() 136 | */ 137 | private String getExtension() { 138 | "ormgap" 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # For Cygwin, ensure paths are in UNIX format before anything is touched. 46 | if $cygwin ; then 47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 48 | fi 49 | 50 | # Attempt to set APP_HOME 51 | # Resolve links: $0 may be a link 52 | PRG="$0" 53 | # Need this for relative symlinks. 54 | while [ -h "$PRG" ] ; do 55 | ls=`ls -ld "$PRG"` 56 | link=`expr "$ls" : '.*-> \(.*\)$'` 57 | if expr "$link" : '/.*' > /dev/null; then 58 | PRG="$link" 59 | else 60 | PRG=`dirname "$PRG"`"/$link" 61 | fi 62 | done 63 | SAVED="`pwd`" 64 | cd "`dirname \"$PRG\"`/" >&- 65 | APP_HOME="`pwd -P`" 66 | cd "$SAVED" >&- 67 | 68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 69 | 70 | # Determine the Java command to use to start the JVM. 71 | if [ -n "$JAVA_HOME" ] ; then 72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 73 | # IBM's JDK on AIX uses strange locations for the executables 74 | JAVACMD="$JAVA_HOME/jre/sh/java" 75 | else 76 | JAVACMD="$JAVA_HOME/bin/java" 77 | fi 78 | if [ ! -x "$JAVACMD" ] ; then 79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 80 | 81 | Please set the JAVA_HOME variable in your environment to match the 82 | location of your Java installation." 83 | fi 84 | else 85 | JAVACMD="java" 86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 87 | 88 | Please set the JAVA_HOME variable in your environment to match the 89 | location of your Java installation." 90 | fi 91 | 92 | # Increase the maximum file descriptors if we can. 93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 94 | MAX_FD_LIMIT=`ulimit -H -n` 95 | if [ $? -eq 0 ] ; then 96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 97 | MAX_FD="$MAX_FD_LIMIT" 98 | fi 99 | ulimit -n $MAX_FD 100 | if [ $? -ne 0 ] ; then 101 | warn "Could not set maximum file descriptor limit: $MAX_FD" 102 | fi 103 | else 104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 105 | fi 106 | fi 107 | 108 | # For Darwin, add options to specify how the application appears in the dock 109 | if $darwin; then 110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 111 | fi 112 | 113 | # For Cygwin, switch paths to Windows format before running java 114 | if $cygwin ; then 115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 158 | function splitJvmOpts() { 159 | JVM_OPTS=("$@") 160 | } 161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 163 | 164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 165 | -------------------------------------------------------------------------------- /gradle/gradle-mvn-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 | } 219 | -------------------------------------------------------------------------------- /ormgap-plugin/src/main/java/com/github/stephanenicolas/ormgap/CreateOrmLiteConfigTask.java: -------------------------------------------------------------------------------- 1 | package com.github.stephanenicolas.ormgap; 2 | 3 | import org.gradle.api.Action; 4 | import org.gradle.api.DefaultTask; 5 | import org.gradle.api.file.ConfigurableFileTree; 6 | import org.gradle.api.file.FileCollection; 7 | import org.gradle.api.tasks.CacheableTask; 8 | import org.gradle.api.tasks.InputFiles; 9 | import org.gradle.api.tasks.OutputFile; 10 | import org.gradle.api.tasks.TaskAction; 11 | import org.gradle.api.tasks.incremental.IncrementalTaskInputs; 12 | import org.gradle.api.tasks.incremental.InputFileDetails; 13 | 14 | import java.io.BufferedReader; 15 | import java.io.File; 16 | import java.io.FileReader; 17 | import java.io.FileWriter; 18 | import java.io.IOException; 19 | import java.io.PrintWriter; 20 | import java.sql.SQLException; 21 | import java.util.ArrayList; 22 | import java.util.HashSet; 23 | import java.util.Set; 24 | import java.util.concurrent.atomic.AtomicBoolean; 25 | 26 | import static java.lang.String.format; 27 | 28 | /** 29 | * Generate an ORM Lite configuration file. 30 | * 31 | * @author SNI 32 | */ 33 | @CacheableTask 34 | public class CreateOrmLiteConfigTask extends DefaultTask { 35 | public static final String TASK_TEMP_FILE__NAME = "intermediates/incremental/createOrmLiteConfigTask/"; 36 | private File configFileName; 37 | private Object sourceDir; 38 | private FileCollection classpath; 39 | private File dstDir; 40 | 41 | public CreateOrmLiteConfigTask() { 42 | } 43 | 44 | @InputFiles 45 | public FileCollection getSources() { 46 | ConfigurableFileTree fileTree = getProject().fileTree(this.sourceDir); 47 | fileTree.include("**/*.java"); 48 | return fileTree; 49 | } 50 | 51 | @InputFiles 52 | public FileCollection getClasspath() { 53 | return classpath; 54 | } 55 | 56 | @OutputFile 57 | public File getOutputFile() { 58 | return new File(dstDir, "ormlite_config.txt"); 59 | } 60 | 61 | @OutputFile 62 | private File getStateFile() { 63 | final File buildDir = getProject().getBuildDir(); 64 | final File taskDir = new File(buildDir, TASK_TEMP_FILE__NAME); 65 | if(!taskDir.exists()) { 66 | taskDir.mkdirs(); 67 | } 68 | return new File(taskDir, "using-ormlite.txt"); 69 | } 70 | 71 | public void setClasspath(FileCollection classpath) throws IOException { 72 | this.classpath = classpath; 73 | } 74 | 75 | public void into(String configFileName) { 76 | this.configFileName = new File(dstDir, configFileName); 77 | } 78 | 79 | public void setSources(Object relativePath) { 80 | this.sourceDir = getProject().file(relativePath); 81 | } 82 | 83 | public void setDestDirFolder(Object relativePath) { 84 | dstDir = getProject().file(relativePath); 85 | if (!dstDir.exists()) { 86 | final boolean wasAssetsDirCreated = dstDir.mkdirs(); 87 | if (!wasAssetsDirCreated) { 88 | throw new RuntimeException("Impossible to create destination folder:" + dstDir.getAbsolutePath()); 89 | } 90 | } 91 | } 92 | 93 | @TaskAction 94 | protected void exec(IncrementalTaskInputs inputs) throws IOException, SQLException, InterruptedException { 95 | if (!inputs.isIncremental()) { 96 | getProject().delete(getOutputFile()); 97 | } 98 | 99 | final Set lastFilesInState = loadFileNames(); 100 | final Set newFilesInState = new HashSet<>(lastFilesInState); 101 | 102 | if (!hasNewState(inputs, lastFilesInState, newFilesInState)) { 103 | return; 104 | } 105 | saveFileNames(newFilesInState); 106 | 107 | final CreateOrmLiteConfigAction createOrmLiteConfigAction 108 | = new CreateOrmLiteConfigAction(configFileName, 109 | getProject().file(sourceDir), 110 | classpath.getAsPath(), getLogger()); 111 | 112 | createOrmLiteConfigAction.execute(); 113 | 114 | this.setDidWork(true); 115 | } 116 | 117 | private boolean hasNewState(IncrementalTaskInputs inputs, final Set lastFilesInState, final Set newFilesInState) { 118 | final AtomicBoolean hasChanged = new AtomicBoolean(false); 119 | inputs.outOfDate(new Action() { 120 | @Override public void execute(InputFileDetails inputFileDetails) { 121 | final String absolutePath = inputFileDetails.getFile().getAbsolutePath(); 122 | if(inputFileDetails.isAdded() && isUsingOrmLite(inputFileDetails.getFile())) { 123 | newFilesInState.add(absolutePath); 124 | hasChanged.set(true); 125 | getLogger().debug("New file using ormlite: " + absolutePath); 126 | } else if (inputFileDetails.isModified() && lastFilesInState.contains(absolutePath)) { 127 | getLogger().debug("Modified file using ormlite: " + absolutePath); 128 | hasChanged.set(true); 129 | } else if(isUsingOrmLite(inputFileDetails.getFile())) { 130 | getLogger().debug("Out of date file using ormlite: " + absolutePath); 131 | newFilesInState.add(absolutePath); 132 | hasChanged.set(true); 133 | } 134 | } 135 | }); 136 | 137 | inputs.removed(new Action() { 138 | @Override public void execute(InputFileDetails inputFileDetails) { 139 | final String absolutePath = inputFileDetails.getFile().getAbsolutePath(); 140 | if(lastFilesInState.contains(absolutePath)) { 141 | getLogger().debug("Removed file using ormlite: " + absolutePath); 142 | newFilesInState.remove(absolutePath); 143 | hasChanged.set(true); 144 | } 145 | 146 | } 147 | }); 148 | return hasChanged.get(); 149 | } 150 | 151 | private void saveFileNames(Set fileNameSet) throws IOException { 152 | getLogger().debug("saving new state: " + fileNameSet.toString()); 153 | final File stateFile = getStateFile(); 154 | PrintWriter fileWriter = null; 155 | try { 156 | fileWriter = new PrintWriter(new FileWriter(stateFile)); 157 | final ArrayList sortedfileNameList = new ArrayList<>(fileNameSet); 158 | for (String fileName : sortedfileNameList) { 159 | fileWriter.println(fileName); 160 | } 161 | } finally { 162 | if(fileWriter!=null) { 163 | fileWriter.close(); 164 | } 165 | } 166 | } 167 | 168 | private Set loadFileNames() throws IOException { 169 | Set files = new HashSet<>(); 170 | final File stateFile = getStateFile(); 171 | if(!stateFile.exists()) { 172 | return files; 173 | } 174 | BufferedReader reader = null; 175 | try { 176 | reader = new BufferedReader(new FileReader(stateFile)); 177 | while (reader.ready()) { 178 | files.add(reader.readLine()); 179 | } 180 | } finally { 181 | if(reader!=null) { 182 | reader.close(); 183 | } 184 | } 185 | getLogger().debug("loading new state: " + files.toString()); 186 | return files; 187 | } 188 | 189 | private boolean isUsingOrmLite(File file) { 190 | if (file.isDirectory()) { 191 | return false; 192 | } 193 | if (!file.exists()) { 194 | throw new RuntimeException(format("File %s doesn't exist.", file.getAbsolutePath())); 195 | } 196 | BufferedReader reader = null; 197 | boolean found = false; 198 | try { 199 | reader = new BufferedReader(new FileReader(file)); 200 | while (reader.ready() && !found) { 201 | if (reader.readLine().contains("com.j256.ormlite")) { 202 | found = true; 203 | } 204 | } 205 | } catch (IOException e) { 206 | e.printStackTrace(); 207 | } finally { 208 | if (reader != null) { 209 | try { 210 | reader.close(); 211 | } catch (IOException e) { 212 | e.printStackTrace(); 213 | } 214 | } 215 | } 216 | return found; 217 | } 218 | } 219 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /ormgap-ormlite-extension/src/main/java/com/github/stephanenicolas/ormgap/OrmLiteConfigUtil.java: -------------------------------------------------------------------------------- 1 | package com.github.stephanenicolas.ormgap; 2 | 3 | import com.j256.ormlite.dao.DaoManager; 4 | import com.j256.ormlite.db.DatabaseType; 5 | import com.j256.ormlite.db.SqliteAndroidDatabaseType; 6 | import com.j256.ormlite.field.DatabaseField; 7 | import com.j256.ormlite.field.DatabaseFieldConfig; 8 | import com.j256.ormlite.field.ForeignCollectionField; 9 | import com.j256.ormlite.table.DatabaseTable; 10 | import com.j256.ormlite.table.DatabaseTableConfig; 11 | import com.j256.ormlite.table.DatabaseTableConfigLoader; 12 | import java.io.BufferedReader; 13 | import java.io.BufferedWriter; 14 | import java.io.File; 15 | import java.io.FileFilter; 16 | import java.io.FileOutputStream; 17 | import java.io.FileReader; 18 | import java.io.IOException; 19 | import java.io.OutputStream; 20 | import java.io.OutputStreamWriter; 21 | import java.lang.reflect.Field; 22 | import java.sql.SQLException; 23 | import java.util.ArrayList; 24 | import java.util.List; 25 | 26 | /** 27 | * Database configuration file helper class that is used to write a configuration file into the raw resource 28 | * sub-directory to speed up DAO creation. 29 | * 30 | *

31 | * With help from the user list and especially Ian Dees, we discovered that calls to annotation methods in Android are 32 | * _very_ expensive because Method.equals() was doing a huge toString(). This was causing folks to see 2-3 seconds 33 | * startup time when configuring 10-15 DAOs because of 1000s of calls to @DatabaseField methods. See this Android bug report. 35 | *

36 | * 37 | *

38 | * I added this utility class which writes a configuration file into the raw resource "res/raw" directory inside of your 39 | * project containing the table and field names and associated details. This file can then be loaded into the 40 | * {@link DaoManager} with the help of the 41 | * {@link OrmLiteSqliteOpenHelper#OrmLiteSqliteOpenHelper(android.content.Context, String, android.database.sqlite.SQLiteDatabase.CursorFactory, int, int)} 42 | * constructor. This means that you can configure your classes _without_ any runtime calls to annotations. It seems 43 | * significantly faster. 44 | *

45 | * 46 | *

47 | * WARNING: Although this is fast, the big problem is that you have to remember to regenerate the config file 48 | * whenever you edit one of your database classes. There is no way that I know of to do this automagically. 49 | *

50 | * 51 | * @author graywatson 52 | */ 53 | public class OrmLiteConfigUtil { 54 | 55 | /** 56 | * Resource directory name that we are looking for. 57 | */ 58 | protected static final String RESOURCE_DIR_NAME = "res"; 59 | /** 60 | * Raw directory name that we are looking for. 61 | */ 62 | protected static final String RAW_DIR_NAME = "raw"; 63 | public static final String HELP_COMMAND = "--help"; 64 | 65 | /** 66 | * Maximum recursion level while we are looking for source files. 67 | */ 68 | protected static int maxFindSourceLevel = 20; 69 | 70 | private static final DatabaseType databaseType = new SqliteAndroidDatabaseType(); 71 | 72 | /** 73 | * A call through to {@link #writeConfigFile(String)} taking the file name from the single command line argument. 74 | */ 75 | public static void main(String[] args) throws Exception { 76 | System.out.println("OrmLiteConfigUtil active"); 77 | if (args.length > 2) { 78 | throw new IllegalArgumentException("TODO review that : Main can take 1 or 2 file-name argument."); 79 | } 80 | 81 | if (args.length == 0 || args[0].equals(HELP_COMMAND)) { 82 | System.out.println("OrmLiteConfigUtil is a Java app that can create ORM Lite configuration to boost ORMLite performances.\n"); 83 | System.out.println("Usages: .\n"); 84 | System.out.println("* ..OrmLiteConfigUtil .\n"); 85 | System.out.println(" will generate the ORMLite config file and scan current folder for classes and res/raw dir.\n"); 86 | System.out.println("* ..OrmLiteConfigUtil .\n"); 87 | System.out.println(" will generate the ORMLite config file and scan the search directory for classes and res/raw dir.\n"); 88 | } 89 | if (args.length == 1) { 90 | String configFileName = args[0]; 91 | writeConfigFile(configFileName); 92 | } else { 93 | File configFile = new File(args[0]); 94 | File searchDir = new File(args[1]); 95 | writeConfigFile(configFile, searchDir); 96 | } 97 | System.out.println("OrmLiteConfigUtil done"); 98 | } 99 | 100 | /** 101 | * Finds the annotated classes in the current directory or below and writes a configuration file to the file-name in 102 | * the raw folder. 103 | */ 104 | public static void writeConfigFile(String fileName) throws SQLException, IOException { 105 | List> classList = new ArrayList>(); 106 | findAnnotatedClasses(classList, new File("."), 0); 107 | writeConfigFile(fileName, classList.toArray(new Class[classList.size()])); 108 | } 109 | 110 | /** 111 | * Writes a configuration fileName in the raw directory with the configuration for classes. 112 | */ 113 | public static void writeConfigFile(String fileName, Class[] classes) throws SQLException, IOException { 114 | File rawDir = findRawDir(new File(".")); 115 | if (rawDir == null) { 116 | System.err.println("Could not find " + RAW_DIR_NAME + " directory which is typically in the " 117 | + RESOURCE_DIR_NAME + " directory"); 118 | } else { 119 | File configFile = new File(rawDir, fileName); 120 | writeConfigFile(configFile, classes); 121 | } 122 | } 123 | 124 | /** 125 | * Finds the annotated classes in the current directory or below and writes a configuration file. 126 | */ 127 | public static void writeConfigFile(File configFile) throws SQLException, IOException { 128 | writeConfigFile(configFile, new File(".")); 129 | } 130 | 131 | /** 132 | * Finds the annotated classes in the specified search directory or below and writes a configuration file. 133 | */ 134 | public static void writeConfigFile(File configFile, File searchDir) throws SQLException, IOException { 135 | List> classList = new ArrayList>(); 136 | findAnnotatedClasses(classList, searchDir, 0); 137 | writeConfigFile(configFile, classList.toArray(new Class[classList.size()])); 138 | } 139 | 140 | /** 141 | * Write a configuration file with the configuration for classes. 142 | */ 143 | public static void writeConfigFile(File configFile, Class[] classes) throws SQLException, IOException { 144 | System.out.println("Writing configurations to " + configFile.getAbsolutePath()); 145 | writeConfigFile(new FileOutputStream(configFile), classes); 146 | } 147 | 148 | /** 149 | * Write a configuration file to an output stream with the configuration for classes. 150 | */ 151 | public static void writeConfigFile(OutputStream outputStream, File searchDir) throws SQLException, IOException { 152 | List> classList = new ArrayList>(); 153 | findAnnotatedClasses(classList, searchDir, 0); 154 | writeConfigFile(outputStream, classList.toArray(new Class[classList.size()])); 155 | } 156 | 157 | /** 158 | * Write a configuration file to an output stream with the configuration for classes. 159 | */ 160 | public static void writeConfigFile(OutputStream outputStream, Class[] classes) throws SQLException, IOException { 161 | BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream), 4096); 162 | try { 163 | for (Class clazz : classes) { 164 | writeConfigForTable(writer, clazz); 165 | } 166 | // NOTE: done is here because this is public 167 | System.out.println("Done."); 168 | } finally { 169 | writer.close(); 170 | } 171 | } 172 | 173 | /** 174 | * Look for the resource-directory in the current directory or the directories above. Then look for the 175 | * raw-directory underneath the resource-directory. 176 | */ 177 | protected static File findRawDir(File dir) { 178 | for (int i = 0; dir != null && i < 20; i++) { 179 | File rawDir = findResRawDir(dir); 180 | if (rawDir != null) { 181 | return rawDir; 182 | } 183 | dir = dir.getParentFile(); 184 | } 185 | return null; 186 | } 187 | 188 | private static void findAnnotatedClasses(List> classList, File dir, int level) throws SQLException, 189 | IOException { 190 | for (File file : dir.listFiles()) { 191 | if (file.isDirectory()) { 192 | // recurse if we aren't deep enough 193 | if (level < maxFindSourceLevel) { 194 | findAnnotatedClasses(classList, file, level + 1); 195 | } 196 | continue; 197 | } 198 | // skip non .java files 199 | if (!file.getName().endsWith(".java")) { 200 | continue; 201 | } 202 | String packageName = getPackageOfClass(file); 203 | if (packageName == null) { 204 | System.err.println("Could not find package name for: " + file); 205 | continue; 206 | } 207 | // get the filename and cut off the .java 208 | String name = file.getName(); 209 | name = name.substring(0, name.length() - ".java".length()); 210 | String className = packageName + "." + name; 211 | Class clazz; 212 | try { 213 | clazz = Class.forName(className); 214 | } catch (Throwable t) { 215 | // amazingly, this sometimes throws an Error 216 | System.err.println("Could not load class file for: " + file); 217 | System.err.println(" " + t); 218 | continue; 219 | } 220 | if (classHasAnnotations(clazz)) { 221 | classList.add(clazz); 222 | } 223 | // handle inner classes 224 | try { 225 | for (Class innerClazz : clazz.getDeclaredClasses()) { 226 | if (classHasAnnotations(innerClazz)) { 227 | classList.add(innerClazz); 228 | } 229 | } 230 | } catch (Throwable t) { 231 | // amazingly, this sometimes throws an Error 232 | System.err.println("Could not load inner classes for: " + clazz); 233 | System.err.println(" " + t); 234 | continue; 235 | } 236 | } 237 | } 238 | 239 | private static void writeConfigForTable(BufferedWriter writer, Class clazz) throws SQLException, IOException { 240 | String tableName = DatabaseTableConfig.extractTableName(clazz); 241 | List fieldConfigs = new ArrayList(); 242 | // walk up the classes finding the fields 243 | try { 244 | for (Class working = clazz; working != null; working = working.getSuperclass()) { 245 | for (Field field : working.getDeclaredFields()) { 246 | DatabaseFieldConfig fieldConfig = DatabaseFieldConfig.fromField(databaseType, tableName, field); 247 | if (fieldConfig != null) { 248 | fieldConfigs.add(fieldConfig); 249 | } 250 | } 251 | } 252 | } catch (Error e) { 253 | System.err.println("Skipping " + clazz + " because we got an error finding its definition: " 254 | + e.getMessage()); 255 | return; 256 | } 257 | if (fieldConfigs.isEmpty()) { 258 | System.out.println("Skipping " + clazz + " because no annotated fields found"); 259 | return; 260 | } 261 | @SuppressWarnings({"rawtypes", "unchecked"}) 262 | DatabaseTableConfig tableConfig = new DatabaseTableConfig(clazz, tableName, fieldConfigs); 263 | DatabaseTableConfigLoader.write(writer, tableConfig); 264 | writer.append("#################################"); 265 | writer.newLine(); 266 | System.out.println("Wrote config for " + clazz); 267 | } 268 | 269 | private static boolean classHasAnnotations(Class clazz) { 270 | while (clazz != null) { 271 | if (clazz.getAnnotation(DatabaseTable.class) != null) { 272 | return true; 273 | } 274 | Field[] fields; 275 | try { 276 | fields = clazz.getDeclaredFields(); 277 | } catch (Throwable t) { 278 | // amazingly, this sometimes throws an Error 279 | System.err.println("Could not load get delcared fields from: " + clazz); 280 | System.err.println(" " + t); 281 | return false; 282 | } 283 | for (Field field : fields) { 284 | if (field.getAnnotation(DatabaseField.class) != null 285 | || field.getAnnotation(ForeignCollectionField.class) != null) { 286 | return true; 287 | } 288 | } 289 | try { 290 | clazz = clazz.getSuperclass(); 291 | } catch (Throwable t) { 292 | // amazingly, this sometimes throws an Error 293 | System.err.println("Could not get super class for: " + clazz); 294 | System.err.println(" " + t); 295 | return false; 296 | } 297 | } 298 | 299 | return false; 300 | } 301 | 302 | /** 303 | * Returns the package name of a file that has one of the annotations we are looking for. 304 | * 305 | * @return Package prefix string or null or no annotations. 306 | */ 307 | private static String getPackageOfClass(File file) throws IOException { 308 | BufferedReader reader = new BufferedReader(new FileReader(file)); 309 | try { 310 | while (true) { 311 | String line = reader.readLine(); 312 | if (line == null) { 313 | return null; 314 | } 315 | if (line.contains("package")) { 316 | String[] parts = line.split("[ \t;]"); 317 | if (parts.length > 1 && parts[0].equals("package")) { 318 | return parts[1]; 319 | } 320 | } 321 | } 322 | } finally { 323 | reader.close(); 324 | } 325 | } 326 | 327 | /** 328 | * Look for the resource directory with raw beneath it. 329 | */ 330 | private static File findResRawDir(File dir) { 331 | for (File file : dir.listFiles()) { 332 | if (file.getName().equals(RESOURCE_DIR_NAME) && file.isDirectory()) { 333 | File[] rawFiles = file.listFiles(new FileFilter() { 334 | public boolean accept(File file) { 335 | return file.getName().equals(RAW_DIR_NAME) && file.isDirectory(); 336 | } 337 | }); 338 | if (rawFiles.length == 1) { 339 | return rawFiles[0]; 340 | } 341 | } 342 | } 343 | return null; 344 | } 345 | } 346 | --------------------------------------------------------------------------------