├── lib ├── .gitignore ├── build.gradle ├── src │ └── main │ │ └── java │ │ └── dk │ │ └── nodes │ │ └── data │ │ └── lib │ │ ├── AnnotatedClass.java │ │ ├── DataProcessor.java │ │ └── CodeGenerator.java └── maven-push.gradle ├── annotation ├── .gitignore ├── build.gradle ├── src │ └── main │ │ └── java │ │ └── dk │ │ └── nodes │ │ └── data │ │ └── annotation │ │ ├── Data.java │ │ ├── Mode.java │ │ └── Persistence.java └── maven-push.gradle ├── dataextras ├── .gitignore ├── src │ ├── main │ │ ├── res │ │ │ └── values │ │ │ │ └── strings.xml │ │ └── AndroidManifest.xml │ ├── test │ │ └── java │ │ │ └── dk │ │ │ └── nodes │ │ │ └── dataextras │ │ │ └── ExampleUnitTest.java │ └── androidTest │ │ └── java │ │ └── dk │ │ └── nodes │ │ └── dataextras │ │ └── ExampleInstrumentedTest.java ├── proguard-rules.pro └── build.gradle ├── exampleproject ├── .gitignore ├── src │ ├── main │ │ ├── res │ │ │ ├── values │ │ │ │ ├── strings.xml │ │ │ │ ├── colors.xml │ │ │ │ ├── dimens.xml │ │ │ │ └── styles.xml │ │ │ ├── mipmap-hdpi │ │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-mdpi │ │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-xhdpi │ │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-xxhdpi │ │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-xxxhdpi │ │ │ │ └── ic_launcher.png │ │ │ ├── values-w820dp │ │ │ │ └── dimens.xml │ │ │ └── layout │ │ │ │ └── activity_main.xml │ │ ├── java │ │ │ └── dk │ │ │ │ └── nodes │ │ │ │ └── exampleproject │ │ │ │ ├── UserData.java │ │ │ │ └── MainActivity.java │ │ └── AndroidManifest.xml │ ├── test │ │ └── java │ │ │ └── dk │ │ │ └── nodes │ │ │ └── exampleproject │ │ │ └── ExampleUnitTest.java │ └── androidTest │ │ └── java │ │ └── dk │ │ └── nodes │ │ └── exampleproject │ │ └── ApplicationTest.java ├── proguard-rules.pro └── build.gradle ├── settings.gradle ├── .idea ├── copyright │ └── profiles_settings.xml ├── encodings.xml ├── inspectionProfiles │ ├── profiles_settings.xml │ └── Project_Default.xml ├── runConfigurations.xml ├── modules.xml ├── compiler.xml ├── gradle.xml └── misc.xml ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── .gitignore ├── gradle.properties ├── README.md ├── gradlew.bat └── gradlew /lib/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /annotation/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /dataextras/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /exampleproject/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':exampleproject', ':lib', ':annotation', ':dataextras' 2 | -------------------------------------------------------------------------------- /.idea/copyright/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ml-archive/data/master/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /dataextras/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | Data Extras 3 | 4 | -------------------------------------------------------------------------------- /exampleproject/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | Exampleproject 3 | 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/workspace.xml 5 | /.idea/libraries 6 | .DS_Store 7 | /build 8 | /captures 9 | -------------------------------------------------------------------------------- /exampleproject/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ml-archive/data/master/exampleproject/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /exampleproject/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ml-archive/data/master/exampleproject/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /exampleproject/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ml-archive/data/master/exampleproject/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /exampleproject/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ml-archive/data/master/exampleproject/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /exampleproject/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ml-archive/data/master/exampleproject/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /.idea/encodings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /exampleproject/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #3F51B5 4 | #303F9F 5 | #FF4081 6 | 7 | -------------------------------------------------------------------------------- /exampleproject/src/main/res/values/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 16dp 4 | 16dp 5 | 6 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Thu Oct 20 17:55:43 CEST 2016 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-2.14.1-all.zip 7 | -------------------------------------------------------------------------------- /.idea/inspectionProfiles/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 7 | -------------------------------------------------------------------------------- /annotation/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'java' 2 | apply plugin: 'signing' 3 | apply plugin: 'maven' 4 | apply plugin: 'maven-publish' 5 | apply from: 'maven-push.gradle' 6 | 7 | sourceCompatibility = JavaVersion.VERSION_1_7 8 | targetCompatibility = JavaVersion.VERSION_1_7 9 | 10 | dependencies { 11 | compile fileTree(dir: 'libs', include: ['*.jar']) 12 | } -------------------------------------------------------------------------------- /dataextras/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /exampleproject/src/main/res/values-w820dp/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 64dp 6 | 7 | -------------------------------------------------------------------------------- /exampleproject/src/test/java/dk/nodes/exampleproject/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package dk.nodes.exampleproject; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * To work on unit tests, switch the Test Artifact in the Build Variants view. 9 | */ 10 | public class ExampleUnitTest { 11 | @Test 12 | public void addition_isCorrect() throws Exception { 13 | assertEquals(4, 2 + 2); 14 | } 15 | } -------------------------------------------------------------------------------- /exampleproject/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /exampleproject/src/androidTest/java/dk/nodes/exampleproject/ApplicationTest.java: -------------------------------------------------------------------------------- 1 | package dk.nodes.exampleproject; 2 | 3 | import android.app.Application; 4 | import android.test.ApplicationTestCase; 5 | 6 | /** 7 | * Testing Fundamentals 8 | */ 9 | public class ApplicationTest extends ApplicationTestCase { 10 | public ApplicationTest() { 11 | super(Application.class); 12 | } 13 | } -------------------------------------------------------------------------------- /annotation/src/main/java/dk/nodes/data/annotation/Data.java: -------------------------------------------------------------------------------- 1 | package dk.nodes.data.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | /** 8 | * Created by joso on 30/05/16. 9 | */ 10 | @Target(ElementType.TYPE) 11 | @Retention(RetentionPolicy.CLASS) 12 | public @interface Data { 13 | Persistence persistence(); 14 | Mode mode(); 15 | } 16 | -------------------------------------------------------------------------------- /annotation/src/main/java/dk/nodes/data/annotation/Mode.java: -------------------------------------------------------------------------------- 1 | package dk.nodes.data.annotation; 2 | 3 | /** 4 | * Created by joso on 31/05/16. 5 | */ 6 | public enum Mode { 7 | SHAREDPREFERENCES(Constants.SHARED_PREFS), FILE(Constants.FILE); 8 | 9 | 10 | Mode(String constant) { 11 | 12 | } 13 | 14 | public static class Constants { 15 | public static final String FILE = "FILE"; 16 | public static final String SHARED_PREFS = "SHARED_PREFS"; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /annotation/src/main/java/dk/nodes/data/annotation/Persistence.java: -------------------------------------------------------------------------------- 1 | package dk.nodes.data.annotation; 2 | 3 | /** 4 | * Created by joso on 30/05/16. 5 | */ 6 | public enum Persistence { 7 | SERIALIZATION(Constants.SERIALIZATION), GSON(Constants.GSON); 8 | 9 | 10 | Persistence(String constant) { 11 | 12 | } 13 | 14 | public static class Constants { 15 | public static final String SERIALIZATION = "SERIALIZATION"; 16 | public static final String GSON = "GSON"; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /dataextras/src/test/java/dk/nodes/dataextras/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package dk.nodes.dataextras; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * @see Testing documentation 11 | */ 12 | public class ExampleUnitTest { 13 | @Test 14 | public void addition_isCorrect() throws Exception { 15 | assertEquals(4, 2 + 2); 16 | } 17 | } -------------------------------------------------------------------------------- /lib/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'java' 2 | apply plugin: 'signing' 3 | apply plugin: 'maven' 4 | apply plugin: 'maven-publish' 5 | apply from: 'maven-push.gradle' 6 | 7 | sourceCompatibility = JavaVersion.VERSION_1_7 8 | targetCompatibility = JavaVersion.VERSION_1_7 9 | 10 | dependencies { 11 | compile 'dk.nodes.data:annotation:0.1' 12 | compile fileTree(dir: 'libs', include: ['*.jar']) 13 | compile 'com.google.auto.service:auto-service:1.0-rc2' 14 | compile 'org.apache.commons:commons-lang3:3.0' 15 | compile 'com.squareup:javapoet:1.7.0' 16 | } -------------------------------------------------------------------------------- /exampleproject/src/main/java/dk/nodes/exampleproject/UserData.java: -------------------------------------------------------------------------------- 1 | package dk.nodes.exampleproject; 2 | 3 | import java.io.Serializable; 4 | 5 | import dk.nodes.data.annotation.Data; 6 | import dk.nodes.data.annotation.Mode; 7 | import dk.nodes.data.annotation.Persistence; 8 | 9 | /** 10 | * Created by joso on 30/05/16. 11 | */ 12 | @Data( 13 | persistence = Persistence.SERIALIZATION, 14 | mode = Mode.FILE 15 | ) 16 | public class UserData implements Serializable { 17 | public String token = ""; 18 | public String userName = ""; 19 | } 20 | -------------------------------------------------------------------------------- /.idea/inspectionProfiles/Project_Default.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 11 | -------------------------------------------------------------------------------- /.idea/runConfigurations.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 11 | 12 | -------------------------------------------------------------------------------- /dataextras/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/joso/sdk/sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /exampleproject/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/joso/sdk/sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /exampleproject/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /.idea/compiler.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 22 | -------------------------------------------------------------------------------- /exampleproject/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 12 | 13 | 18 | 19 | -------------------------------------------------------------------------------- /dataextras/src/androidTest/java/dk/nodes/dataextras/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package dk.nodes.dataextras; 2 | 3 | import android.content.Context; 4 | import android.support.test.InstrumentationRegistry; 5 | import android.support.test.runner.AndroidJUnit4; 6 | 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | 10 | import static org.junit.Assert.*; 11 | 12 | /** 13 | * Instrumentation test, which will execute on an Android device. 14 | * 15 | * @see Testing documentation 16 | */ 17 | @RunWith(AndroidJUnit4.class) 18 | public class ExampleInstrumentedTest { 19 | @Test 20 | public void useAppContext() throws Exception { 21 | // Context of the app under test. 22 | Context appContext = InstrumentationRegistry.getTargetContext(); 23 | 24 | assertEquals("dk.nodes.dataextras.test", appContext.getPackageName()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m 13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 14 | 15 | # When configured, Gradle will run in incubating parallel mode. 16 | # This option should only be used with decoupled projects. More details, visit 17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 18 | # org.gradle.parallel=true -------------------------------------------------------------------------------- /exampleproject/src/main/java/dk/nodes/exampleproject/MainActivity.java: -------------------------------------------------------------------------------- 1 | package dk.nodes.exampleproject; 2 | 3 | import android.os.Bundle; 4 | import android.support.v7.app.AppCompatActivity; 5 | import android.widget.TextView; 6 | 7 | public class MainActivity extends AppCompatActivity { 8 | 9 | private TextView textView; 10 | 11 | @Override 12 | protected void onCreate(Bundle savedInstanceState) { 13 | super.onCreate(savedInstanceState); 14 | setContentView(R.layout.activity_main); 15 | 16 | textView = (TextView) findViewById(R.id.textView); 17 | 18 | 19 | UserDataManager userDataManager = new UserDataManager(this.getApplicationContext()); 20 | UserData userData = userDataManager.load(); 21 | userData.userName = "test"; 22 | userDataManager.save(userData); 23 | 24 | userData = userDataManager.load(); 25 | textView.setText(userData.userName); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /.idea/gradle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 21 | 22 | -------------------------------------------------------------------------------- /dataextras/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | 3 | android { 4 | compileSdkVersion 25 5 | buildToolsVersion "25.0.2" 6 | 7 | defaultConfig { 8 | minSdkVersion 17 9 | targetSdkVersion 24 10 | versionCode 1 11 | versionName "1.0" 12 | 13 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 14 | 15 | } 16 | buildTypes { 17 | release { 18 | minifyEnabled false 19 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 20 | } 21 | } 22 | } 23 | 24 | dependencies { 25 | compile fileTree(dir: 'libs', include: ['*.jar']) 26 | androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { 27 | exclude group: 'com.android.support', module: 'support-annotations' 28 | }) 29 | compile 'com.android.support:appcompat-v7:25.0.1' 30 | testCompile 'junit:junit:4.12' 31 | } 32 | -------------------------------------------------------------------------------- /exampleproject/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | apply plugin: 'com.neenbedankt.android-apt' 3 | 4 | android { 5 | compileSdkVersion 23 6 | buildToolsVersion "23.0.3" 7 | 8 | defaultConfig { 9 | applicationId "dk.nodes.exampleproject" 10 | minSdkVersion 23 11 | targetSdkVersion 23 12 | versionCode 1 13 | versionName "1.0" 14 | } 15 | buildTypes { 16 | release { 17 | minifyEnabled false 18 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 19 | } 20 | } 21 | } 22 | 23 | dependencies { 24 | compile fileTree(dir: 'libs', include: ['*.jar']) 25 | testCompile 'junit:junit:4.12' 26 | compile 'com.android.support:appcompat-v7:23.4.0' 27 | compile 'javax.inject:javax.inject:1' 28 | compile 'javax.annotation:javax.annotation-api:1.2' 29 | compile project(':annotation') 30 | apt project(':lib') 31 | provided 'org.glassfish:javax.annotation:10.0-b28' 32 | compile 'com.google.code.gson:gson:2.2.+' 33 | } 34 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Data 2 | 3 | Persistence framework for Android with output methods for the time being Gson or Java Serialization to either files or `SharedPreferences`. 4 | 5 | ## Usage 6 | ```compile 'dk.nodes.data:processor:0.3'``` 7 | 8 | ## Example 9 | 10 | Consider the following class: 11 | ```java 12 | public class UserData { 13 | public String token = ""; 14 | public String userName = ""; 15 | } 16 | ``` 17 | We can either serialize it to disk: 18 | ```java 19 | @Data( 20 | persistence = Persistence.SERIALIZATION, 21 | mode = Mode.FILE 22 | ) 23 | public class UserData implements Serializable { 24 | public String token = ""; 25 | public String userName = ""; 26 | } 27 | ``` 28 | Or save it to `SharedPreferences`: 29 | ```java 30 | @Data( 31 | persistence = Persistence.GSON, 32 | mode = Mode.SHAREDPREFERENCES 33 | ) 34 | public class UserData { 35 | public String token = ""; 36 | public String userName = ""; 37 | } 38 | ``` 39 | Both of these classes will generate a Manager class which can `load` and `save`: 40 | ```java 41 | UserDataManager userDataManager = new UserDataManager(this.getApplicationContext()); 42 | UserData userData = userDataManager.load(); 43 | ... 44 | userDataManager.save(userData); 45 | ``` 46 | 47 | Every `@Data` annoated class will generate a `Manager` through annotation processing. 48 | -------------------------------------------------------------------------------- /lib/src/main/java/dk/nodes/data/lib/AnnotatedClass.java: -------------------------------------------------------------------------------- 1 | package dk.nodes.data.lib; 2 | 3 | /* 4 | * Copyright (C) 2015 Hannes Dorfmann 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | import javax.lang.model.element.TypeElement; 20 | 21 | import dk.nodes.data.annotation.Data; 22 | import dk.nodes.data.annotation.Mode; 23 | import dk.nodes.data.annotation.Persistence; 24 | 25 | /** 26 | * Holds the information about a class annotated with @Data 27 | * 28 | * @author Hannes Dorfmann (Changes by joso@nodes.dk) 29 | */ 30 | public class AnnotatedClass { 31 | 32 | private TypeElement annotatedClassElement; 33 | private Persistence persistence; 34 | private Mode mode; 35 | 36 | public AnnotatedClass(TypeElement classElement) { 37 | this.annotatedClassElement = classElement; 38 | Data annotation = classElement.getAnnotation(Data.class); 39 | persistence = annotation.persistence(); 40 | mode = annotation.mode(); 41 | } 42 | 43 | /** 44 | * 45 | * @return Persistence mode (enum) 46 | */ 47 | public Persistence getPersistence() { 48 | return persistence; 49 | } 50 | 51 | /** 52 | * @return Mode save method (enum) 53 | */ 54 | public Mode getMode() { 55 | return mode; 56 | } 57 | 58 | /** 59 | * @return File name (string) in format data_%s_file 60 | */ 61 | public String getKey() { 62 | return String.format("data_%s_file", annotatedClassElement.getSimpleName().toString()); 63 | } 64 | 65 | /** 66 | * The original element that was annotated with @Factory 67 | */ 68 | public TypeElement getTypeElement() { 69 | return annotatedClassElement; 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /lib/maven-push.gradle: -------------------------------------------------------------------------------- 1 | // Username & password for Sonatype, stored in gradle.properties 2 | def _ossrhUsername = this.properties['NEXUS_USERNAME'] 3 | def _ossrhPassword = this.properties['NEXUS_PASSWORD'] 4 | 5 | // Artifact settings 6 | def _group = 'dk.nodes.data' 7 | def _version = '0.3' 8 | def _archivesBaseName = 'processor' 9 | 10 | def _name = 'Data annotation processor' 11 | def _description = 'Annotation processor for the Data framework from Nodes' 12 | 13 | 14 | afterEvaluate { project -> 15 | uploadArchives { 16 | repositories { 17 | mavenDeployer { 18 | beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) } 19 | 20 | pom.groupId = _group 21 | pom.artifactId = _archivesBaseName 22 | pom.version = _version 23 | 24 | repository(url: "https://oss.sonatype.org/service/local/staging/deploy/maven2/") { 25 | authentication(userName: _ossrhUsername, password: _ossrhPassword) 26 | } 27 | 28 | snapshotRepository(url: "https://oss.sonatype.org/content/repositories/snapshots/") { 29 | authentication(userName: _ossrhUsername, password: _ossrhPassword) 30 | } 31 | 32 | pom.project { 33 | name _name 34 | packaging 'jar' 35 | description _description 36 | url 'https://github.com/nodes-android/data' 37 | inceptionYear '2016' 38 | 39 | scm { 40 | url 'https://github.com/nodes-android/data' 41 | connection 'scm:https://github.com/nodes-android/data.git' 42 | } 43 | 44 | licenses { 45 | license { 46 | name 'The Apache License, Version 2.0' 47 | url 'http://www.apache.org/licenses/LICENSE-2.0.txt' 48 | } 49 | } 50 | 51 | developers { 52 | developer { 53 | id 'johsoe' 54 | name 'Johnny Sørensen' 55 | email 'joso@nodes.dk' 56 | } 57 | } 58 | 59 | issueManagement { 60 | system 'GitHub issues' 61 | url 'https://github.com/nodes-android/data/issues' 62 | } 63 | } 64 | } 65 | } 66 | } 67 | 68 | signing { 69 | required { gradle.taskGraph.hasTask("uploadArchives") } 70 | sign configurations.archives 71 | } 72 | 73 | task androidJavadocs(type: Javadoc) { 74 | source = sourceSets.main.allJava 75 | } 76 | 77 | task androidJavadocsJar(type: Jar, dependsOn: androidJavadocs) { 78 | classifier = 'javadoc' 79 | from androidJavadocs.destinationDir 80 | } 81 | 82 | task sourcesJar(type: Jar) { 83 | classifier = 'sources' 84 | from sourceSets.main.allSource 85 | } 86 | 87 | artifacts { 88 | archives sourcesJar, androidJavadocsJar 89 | } 90 | 91 | } -------------------------------------------------------------------------------- /annotation/maven-push.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'signing' 2 | apply plugin: 'maven' 3 | 4 | // Username & password for Sonatype, stored in gradle.properties 5 | def _ossrhUsername = this.properties['NEXUS_USERNAME'] 6 | def _ossrhPassword = this.properties['NEXUS_PASSWORD'] 7 | 8 | // Artifact settings 9 | def _group = 'dk.nodes.data' 10 | def _version = '0.3' 11 | def _archivesBaseName = 'annotation' 12 | 13 | def _name = 'Data annotations' 14 | def _description = 'Annotations for the Data framework from Nodes' 15 | 16 | 17 | afterEvaluate { project -> 18 | uploadArchives { 19 | repositories { 20 | mavenDeployer { 21 | beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) } 22 | 23 | pom.groupId = _group 24 | pom.artifactId = _archivesBaseName 25 | pom.version = _version 26 | 27 | repository(url: "https://oss.sonatype.org/service/local/staging/deploy/maven2/") { 28 | authentication(userName: _ossrhUsername, password: _ossrhPassword) 29 | } 30 | 31 | snapshotRepository(url: "https://oss.sonatype.org/content/repositories/snapshots/") { 32 | authentication(userName: _ossrhUsername, password: _ossrhPassword) 33 | } 34 | 35 | pom.project { 36 | name _name 37 | packaging 'jar' 38 | description _description 39 | url 'https://github.com/nodes-android/data' 40 | inceptionYear '2016' 41 | 42 | scm { 43 | url 'https://github.com/nodes-android/data' 44 | connection 'scm:https://github.com/nodes-android/data.git' 45 | } 46 | 47 | licenses { 48 | license { 49 | name 'The Apache License, Version 2.0' 50 | url 'http://www.apache.org/licenses/LICENSE-2.0.txt' 51 | } 52 | } 53 | 54 | developers { 55 | developer { 56 | id 'johsoe' 57 | name 'Johnny Sørensen' 58 | email 'joso@nodes.dk' 59 | } 60 | } 61 | 62 | issueManagement { 63 | system 'GitHub issues' 64 | url 'https://github.com/nodes-android/data/issues' 65 | } 66 | } 67 | } 68 | } 69 | } 70 | 71 | signing { 72 | required { gradle.taskGraph.hasTask("uploadArchives") } 73 | sign configurations.archives 74 | } 75 | 76 | task androidJavadocs(type: Javadoc) { 77 | source = sourceSets.main.allJava 78 | } 79 | 80 | task androidJavadocsJar(type: Jar, dependsOn: androidJavadocs) { 81 | classifier = 'javadoc' 82 | from androidJavadocs.destinationDir 83 | } 84 | 85 | task sourcesJar(type: Jar) { 86 | classifier = 'sources' 87 | from sourceSets.main.allSource 88 | } 89 | 90 | artifacts { 91 | archives sourcesJar, androidJavadocsJar 92 | } 93 | 94 | } -------------------------------------------------------------------------------- /lib/src/main/java/dk/nodes/data/lib/DataProcessor.java: -------------------------------------------------------------------------------- 1 | package dk.nodes.data.lib; 2 | 3 | import com.google.auto.service.AutoService; 4 | 5 | import java.util.HashMap; 6 | import java.util.LinkedHashSet; 7 | import java.util.Map; 8 | import java.util.Set; 9 | 10 | import javax.annotation.processing.AbstractProcessor; 11 | import javax.annotation.processing.Filer; 12 | import javax.annotation.processing.Messager; 13 | import javax.annotation.processing.ProcessingEnvironment; 14 | import javax.annotation.processing.Processor; 15 | import javax.annotation.processing.RoundEnvironment; 16 | import javax.lang.model.SourceVersion; 17 | import javax.lang.model.element.Element; 18 | import javax.lang.model.element.ElementKind; 19 | import javax.lang.model.element.TypeElement; 20 | import javax.lang.model.util.Elements; 21 | import javax.lang.model.util.Types; 22 | import javax.tools.Diagnostic; 23 | 24 | import dk.nodes.data.annotation.Data; 25 | import dk.nodes.data.annotation.Mode; 26 | import dk.nodes.data.annotation.Persistence; 27 | 28 | /** 29 | * Thanks for the awesome tutorial: http://hannesdorfmann.com/annotation-processing/annotationprocessing101 30 | */ 31 | @AutoService(Processor.class) 32 | public class DataProcessor extends AbstractProcessor { 33 | 34 | private Types typeUtils; 35 | private Elements elementUtils; 36 | private Filer filer; 37 | private Messager messager; 38 | private Map annotatedClasses = new HashMap<>(); 39 | 40 | @Override 41 | public synchronized void init(ProcessingEnvironment env) { 42 | super.init(env); 43 | typeUtils = processingEnv.getTypeUtils(); 44 | elementUtils = processingEnv.getElementUtils(); 45 | filer = processingEnv.getFiler(); 46 | messager = processingEnv.getMessager(); 47 | } 48 | 49 | @Override 50 | public boolean process(Set annotations, RoundEnvironment env) { 51 | try { 52 | // Scan classes 53 | for (Element annotatedElement : env.getElementsAnnotatedWith(Data.class)) { 54 | 55 | // Check if a class has been annotated with @Data 56 | if (annotatedElement.getKind() != ElementKind.CLASS) { 57 | continue; 58 | } 59 | 60 | // We can cast it, because we know that it of ElementKind.CLASS 61 | TypeElement typeElement = (TypeElement) annotatedElement; 62 | 63 | AnnotatedClass annotatedClass = new AnnotatedClass(typeElement); 64 | 65 | if( annotatedClasses.containsKey(typeElement.getSimpleName()) ) { 66 | error(typeElement, String.format("Already contains an element %s, cant create duplicate managers.")); 67 | return false; 68 | } 69 | 70 | annotatedClasses.put(typeElement.getSimpleName().toString(), annotatedClass); 71 | } 72 | 73 | // Generate code 74 | for (AnnotatedClass annotatedClass : annotatedClasses.values()) { 75 | if( annotatedClass.getPersistence().equals(Persistence.SERIALIZATION) ) { 76 | 77 | if( annotatedClass.getMode().equals(Mode.FILE) ) { 78 | CodeGenerator.generateSerializedFileCode(elementUtils, filer, annotatedClass); 79 | } else { 80 | CodeGenerator.generateSerializedPrefsCode(elementUtils, filer, annotatedClass); 81 | } 82 | 83 | } 84 | 85 | else if( annotatedClass.getPersistence().equals(Persistence.GSON) ) { 86 | if (annotatedClass.getMode().equals(Mode.FILE)) { 87 | CodeGenerator.generateGsonFileCode(elementUtils, filer, annotatedClass); 88 | } else { 89 | CodeGenerator.generateGsonPrefsCode(elementUtils, filer, annotatedClass); 90 | } 91 | } 92 | } 93 | 94 | // We can have several rounds of compilation, so avoid duplicates 95 | annotatedClasses.clear(); 96 | } catch (Exception e) { 97 | throw new RuntimeException(e.toString()); 98 | //error(null, e.getMessage()); 99 | } 100 | 101 | return true; 102 | } 103 | 104 | /** 105 | * Prints an error message 106 | * 107 | * @param e The element which has caused the error. Can be null 108 | * @param msg The error message 109 | */ 110 | public void error(Element e, String msg) { 111 | messager.printMessage(Diagnostic.Kind.ERROR, msg, e); 112 | } 113 | 114 | @Override 115 | public Set getSupportedAnnotationTypes() { 116 | Set annotataions = new LinkedHashSet(); 117 | annotataions.add(Data.class.getCanonicalName()); 118 | return annotataions; 119 | } 120 | 121 | @Override 122 | public SourceVersion getSupportedSourceVersion() { 123 | return SourceVersion.latestSupported(); 124 | } 125 | 126 | } 127 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 19 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | Abstraction issuesJava 39 | 40 | 41 | Android 42 | 43 | 44 | Android > Lint > Correctness 45 | 46 | 47 | Android > Lint > Internationalization > Bidirectional Text 48 | 49 | 50 | Android > Lint > Performance 51 | 52 | 53 | Bitwise operation issuesJava 54 | 55 | 56 | C/C++ 57 | 58 | 59 | Class metricsJava 60 | 61 | 62 | Class structureJava 63 | 64 | 65 | Code style issuesJava 66 | 67 | 68 | Control FlowGroovy 69 | 70 | 71 | Control flow issuesJava 72 | 73 | 74 | Data flow issuesJava 75 | 76 | 77 | Declaration redundancyJava 78 | 79 | 80 | Encapsulation issuesJava 81 | 82 | 83 | GeneralC/C++ 84 | 85 | 86 | Groovy 87 | 88 | 89 | Inheritance issuesJava 90 | 91 | 92 | Internationalization issuesJava 93 | 94 | 95 | J2ME issuesJava 96 | 97 | 98 | JUnit issuesJava 99 | 100 | 101 | Java 102 | 103 | 104 | Java language level migration aidsJava 105 | 106 | 107 | Logging issuesJava 108 | 109 | 110 | Naming ConventionsGroovy 111 | 112 | 113 | Naming conventionsJava 114 | 115 | 116 | Numeric issuesJava 117 | 118 | 119 | Performance issuesJava 120 | 121 | 122 | Probable bugsJava 123 | 124 | 125 | Security issuesJava 126 | 127 | 128 | 129 | 130 | ConstantConditions 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 152 | 153 | 154 | 155 | 156 | 1.7 157 | 158 | 163 | 164 | 165 | 166 | 167 | 168 | -------------------------------------------------------------------------------- /lib/src/main/java/dk/nodes/data/lib/CodeGenerator.java: -------------------------------------------------------------------------------- 1 | package dk.nodes.data.lib; 2 | 3 | import com.squareup.javapoet.ClassName; 4 | import com.squareup.javapoet.JavaFile; 5 | import com.squareup.javapoet.MethodSpec; 6 | import com.squareup.javapoet.TypeSpec; 7 | 8 | import java.io.IOException; 9 | 10 | import javax.annotation.processing.Filer; 11 | import javax.lang.model.element.Modifier; 12 | import javax.lang.model.element.PackageElement; 13 | import javax.lang.model.util.Elements; 14 | /** 15 | * Created by joso on 30/05/16. 16 | */ 17 | public class CodeGenerator { 18 | 19 | private static final String SUFFIX = "Manager"; 20 | 21 | private static String getPackageName(Elements elementUtils, AnnotatedClass annotatedClass) { 22 | PackageElement pkg = elementUtils.getPackageOf(annotatedClass.getTypeElement()); 23 | String packageName = pkg.isUnnamed() ? null : pkg.getQualifiedName().toString(); 24 | return packageName; 25 | } 26 | 27 | public static void generateSerializedFileCode(Elements elementUtils, Filer filer, AnnotatedClass annotatedClass) throws IOException { 28 | String generatedClassName = annotatedClass.getTypeElement().getSimpleName() + SUFFIX; 29 | String packageName = getPackageName(elementUtils, annotatedClass); 30 | 31 | MethodSpec saveMethod = MethodSpec.methodBuilder("save") 32 | .addJavadoc("Writes object to openFileOutput().\n") 33 | .addParameter(ClassName.get(packageName, annotatedClass.getTypeElement().getSimpleName().toString()), "data") 34 | .addCode("" + 35 | "try {\n" + 36 | "\tfos = context.openFileOutput(\""+annotatedClass.getKey()+"\", Context.MODE_PRIVATE);\n" + 37 | "\tos = new ObjectOutputStream(fos);\n" + 38 | "\tos.writeObject(data);\n" + 39 | "\tos.close();\n" + 40 | "} catch(Exception e) {\n" + 41 | "\t// Empty\n" + 42 | "}\n" 43 | ) 44 | .addModifiers(Modifier.PUBLIC) 45 | .build(); 46 | 47 | MethodSpec loadMethod = MethodSpec.methodBuilder("load") 48 | .returns(ClassName.get(annotatedClass.getTypeElement())) 49 | .addJavadoc("Reads object from openFileInput().\n") 50 | .addJavadoc("@return " + annotatedClass.getTypeElement().getSimpleName() + " In case an exception is thrown, returns {@code new " + annotatedClass.getTypeElement().getSimpleName() + "()}\n") 51 | .addCode("" + 52 | "try {\n" + 53 | "\tfis = context.openFileInput(\""+annotatedClass.getKey()+"\");\n" + 54 | "\tis = new ObjectInputStream(fis);\n" + 55 | "\tObject input = is.readObject();\n" + 56 | "\tis.close();\n" + 57 | "\treturn ("+annotatedClass.getTypeElement().getSimpleName()+") input;\n" + 58 | "} catch(Exception e) {\n" + 59 | "\treturn new " + annotatedClass.getTypeElement().getSimpleName() + "();\n" + 60 | "}\n" 61 | ) 62 | .addModifiers(Modifier.PUBLIC) 63 | .build(); 64 | 65 | TypeSpec manager = TypeSpec.classBuilder(generatedClassName) 66 | .addModifiers(Modifier.PUBLIC, Modifier.FINAL) 67 | .addField(ClassName.get("java.io", "FileInputStream"), "fis", Modifier.PRIVATE) 68 | .addField(ClassName.get("java.io", "ObjectInputStream"), "is", Modifier.PRIVATE) 69 | .addField(ClassName.get("java.io", "FileOutputStream"), "fos", Modifier.PRIVATE) 70 | .addField(ClassName.get("java.io", "ObjectOutputStream"), "os", Modifier.PRIVATE) 71 | .addField(ClassName.get("android.content", "Context"), "context", Modifier.PRIVATE) 72 | .addMethod(loadMethod) 73 | .addMethod(saveMethod) 74 | .addMethod(generateContextConstructor()) 75 | .build(); 76 | 77 | // Write file 78 | JavaFile file = JavaFile.builder(packageName, manager).build(); 79 | file.writeTo(filer); 80 | } 81 | 82 | public static void generateSerializedPrefsCode(Elements elementUtils, Filer filer, AnnotatedClass annotatedClass) throws IOException { 83 | String generatedClassName = annotatedClass.getTypeElement().getSimpleName() + SUFFIX; 84 | String packageName = getPackageName(elementUtils, annotatedClass); 85 | 86 | MethodSpec saveMethod = MethodSpec.methodBuilder("save") 87 | .addJavadoc("Writes object to SharedPreferences.\n") 88 | .addParameter(ClassName.get(packageName, annotatedClass.getTypeElement().getSimpleName().toString()), "data") 89 | .addCode("" + 90 | "try {\n" + 91 | "\tsharedPreferences = context.getSharedPreferences(\"appprefs\", Context.MODE_PRIVATE);\n" + 92 | "\tbos = new ByteArrayOutputStream();\n" + 93 | "\tos = new ObjectOutputStream( bos );\n" + 94 | "\tos.writeObject(data);\n" + 95 | "\tString encodedString = Base64.encodeToString(bos.toByteArray(), Base64.DEFAULT);\n" + 96 | "\tSharedPreferences.Editor editor = sharedPreferences.edit();\n" + 97 | "\teditor.putString(\""+ annotatedClass.getKey()+"\", encodedString);\n" + 98 | "\teditor.commit();\n" + 99 | "\tbos.close();\n" + 100 | "} catch(Exception e) {\n" + 101 | "\t// Empty\n" + 102 | "}\n" 103 | ) 104 | .addModifiers(Modifier.PUBLIC) 105 | .build(); 106 | 107 | MethodSpec loadMethod = MethodSpec.methodBuilder("load") 108 | .returns(ClassName.get(annotatedClass.getTypeElement())) 109 | .addJavadoc("Reads object from SharedPreferences.\n") 110 | .addJavadoc("@return " + annotatedClass.getTypeElement().getSimpleName() + " In case an exception is thrown, returns {@code new " + annotatedClass.getTypeElement().getSimpleName() + "()}\n") 111 | .addCode("" + 112 | "try {\n" + 113 | "\tsharedPreferences = context.getSharedPreferences(\"appprefs\", Context.MODE_PRIVATE);\n" + 114 | "\tString inputString = sharedPreferences.getString(\"" + annotatedClass.getKey() + "\", \"nothing\");\n" + 115 | "\tbyte[] byteData = Base64.decode(inputString, Base64.DEFAULT);\n" + 116 | "\tbis = new ByteArrayInputStream(byteData);\n" + 117 | "\tis = new ObjectInputStream(bis);\n" + 118 | "\tObject input = is.readObject();\n" + 119 | "\tbis.close();\n" + 120 | "\treturn (" + annotatedClass.getTypeElement().getSimpleName() + ") input;\n" + 121 | "} catch(Exception e) {\n" + 122 | "\treturn new " + annotatedClass.getTypeElement().getSimpleName() + "();\n" + 123 | "}\n" 124 | ) 125 | .addModifiers(Modifier.PUBLIC) 126 | .build(); 127 | 128 | TypeSpec manager = TypeSpec.classBuilder(generatedClassName) 129 | .addModifiers(Modifier.PUBLIC, Modifier.FINAL) 130 | .addField(ClassName.get("java.io", "ObjectInputStream"), "is", Modifier.PRIVATE) 131 | .addField(ClassName.get("java.io", "ObjectOutputStream"), "os", Modifier.PRIVATE) 132 | .addField(ClassName.get("java.io", "ByteArrayInputStream"), "bis", Modifier.PRIVATE) 133 | .addField(ClassName.get("java.io", "ByteArrayOutputStream"), "bos", Modifier.PRIVATE) 134 | .addField(ClassName.get("android.util", "Base64"), "base64", Modifier.PRIVATE) 135 | .addField(ClassName.get("android.content", "SharedPreferences"), "sharedPreferences", Modifier.PRIVATE) 136 | .addField(ClassName.get("android.content", "Context"), "context", Modifier.PRIVATE) 137 | .addMethod(loadMethod) 138 | .addMethod(saveMethod) 139 | .addMethod(generateContextConstructor()) 140 | .build(); 141 | 142 | // Write file 143 | JavaFile file = JavaFile.builder(packageName, manager).build(); 144 | file.writeTo(filer); 145 | } 146 | 147 | public static void generateGsonPrefsCode(Elements elementUtils, Filer filer, AnnotatedClass annotatedClass) throws IOException { 148 | String generatedClassName = annotatedClass.getTypeElement().getSimpleName() + SUFFIX; 149 | String packageName = getPackageName(elementUtils, annotatedClass); 150 | 151 | MethodSpec saveMethod = MethodSpec.methodBuilder("save") 152 | .addJavadoc("Writes object to SharedPreferences.\n") 153 | .addParameter(ClassName.get(packageName, annotatedClass.getTypeElement().getSimpleName().toString()), "data") 154 | .addCode("" + 155 | "try {\n" + 156 | "\tgson = new Gson();\n" + 157 | "\tsharedPreferences = context.getSharedPreferences(\"appprefs\", Context.MODE_PRIVATE);\n" + 158 | "\tString s = gson.toJson(data);\n" + 159 | "\tSharedPreferences.Editor editor = sharedPreferences.edit();\n" + 160 | "\teditor.putString(\"" + annotatedClass.getKey() + "\", s);\n" + 161 | "\teditor.commit();\n" + 162 | "} catch(Exception e) {\n" + 163 | "\t// Empty\n" + 164 | "}\n" 165 | ) 166 | .addModifiers(Modifier.PUBLIC) 167 | .build(); 168 | 169 | MethodSpec loadMethod = MethodSpec.methodBuilder("load") 170 | .returns(ClassName.get(annotatedClass.getTypeElement())) 171 | .addJavadoc("Reads object from SharedPreferences.\n") 172 | .addJavadoc("@return " + annotatedClass.getTypeElement().getSimpleName() + " In case an exception is thrown, returns {@code new " + annotatedClass.getTypeElement().getSimpleName() + "()}\n") 173 | .addCode("" + 174 | "try {\n" + 175 | "\tgson = new Gson();\n" + 176 | "\tsharedPreferences = context.getSharedPreferences(\"appprefs\", Context.MODE_PRIVATE);\n" + 177 | "\tString inputString = sharedPreferences.getString(\"" + annotatedClass.getKey() + "\", \"nothing\");\n" + 178 | "\tObject input = gson.fromJson(inputString, " + annotatedClass.getTypeElement().getSimpleName() + ".class);\n" + 179 | "\treturn (" + annotatedClass.getTypeElement().getSimpleName() + ") input;\n" + 180 | "} catch(Exception e) {\n" + 181 | "\treturn new " + annotatedClass.getTypeElement().getSimpleName() + "();\n" + 182 | "}\n" 183 | ) 184 | .addModifiers(Modifier.PUBLIC) 185 | .build(); 186 | 187 | TypeSpec manager = TypeSpec.classBuilder(generatedClassName) 188 | .addModifiers(Modifier.PUBLIC, Modifier.FINAL) 189 | .addField(ClassName.get("com.google.gson", "Gson"), "gson", Modifier.PRIVATE) 190 | .addField(ClassName.get("android.content", "SharedPreferences"), "sharedPreferences", Modifier.PRIVATE) 191 | .addField(ClassName.get("android.content", "Context"), "context", Modifier.PRIVATE) 192 | .addMethod(loadMethod) 193 | .addMethod(saveMethod) 194 | .addMethod(generateContextConstructor()) 195 | .build(); 196 | 197 | // Write file 198 | JavaFile file = JavaFile.builder(packageName, manager).build(); 199 | file.writeTo(filer); 200 | } 201 | 202 | public static void generateGsonFileCode(Elements elementUtils, Filer filer, AnnotatedClass annotatedClass) throws IOException { 203 | String generatedClassName = annotatedClass.getTypeElement().getSimpleName() + SUFFIX; 204 | String packageName = getPackageName(elementUtils, annotatedClass); 205 | 206 | MethodSpec saveMethod = MethodSpec.methodBuilder("save") 207 | .addJavadoc("Writes object to openFileOutput().\n") 208 | .addParameter(ClassName.get(packageName, annotatedClass.getTypeElement().getSimpleName().toString()), "data") 209 | .addCode("" + 210 | "try {\n" + 211 | "\tgson = new Gson();\n" + 212 | "\tString s = gson.toJson(data);\n" + 213 | "\tosw = new OutputStreamWriter(context.openFileOutput(\"" + annotatedClass.getKey() + "\", Context.MODE_PRIVATE));\n" + 214 | "\tosw.write(s);\n" + 215 | "\tosw.close();\n" + 216 | "} catch(Exception e) {\n" + 217 | "\t// Empty\n" + 218 | "}\n" 219 | ) 220 | .addModifiers(Modifier.PUBLIC) 221 | .build(); 222 | 223 | MethodSpec loadMethod = MethodSpec.methodBuilder("load") 224 | .returns(ClassName.get(annotatedClass.getTypeElement())) 225 | .addJavadoc("Reads object from openFileInput().\n") 226 | .addJavadoc("@return " + annotatedClass.getTypeElement().getSimpleName() + " In case an exception is thrown, returns {@code new " + annotatedClass.getTypeElement().getSimpleName() + "()}\n") 227 | .addCode("" + 228 | "try {\n" + 229 | "\tfis = context.openFileInput(\"" + annotatedClass.getKey() + "\");\n" + 230 | "\tbr = new BufferedReader(new InputStreamReader(fis));\n" + 231 | "\tStringBuilder sb = new StringBuilder();\n" + 232 | "\tString line;\n" + 233 | "\twhile ((line = br.readLine()) != null) {\n" + 234 | "\t\tsb.append(line);\n" + 235 | "\t}\n" + 236 | "\tString json = sb.toString();\n" + 237 | "\tObject input = gson.fromJson(json, Object.class);\n" + 238 | "\tbr.close();\n" + 239 | "\treturn (" + annotatedClass.getTypeElement().getSimpleName() + ") input;\n" + 240 | "} catch(Exception e) {\n" + 241 | "\treturn new " + annotatedClass.getTypeElement().getSimpleName() + "();\n" + 242 | "}\n" 243 | ) 244 | .addModifiers(Modifier.PUBLIC) 245 | .build(); 246 | 247 | TypeSpec manager = TypeSpec.classBuilder(generatedClassName) 248 | .addModifiers(Modifier.PUBLIC, Modifier.FINAL) 249 | .addField(ClassName.get("java.io", "FileInputStream"), "fis", Modifier.PRIVATE) 250 | .addField(ClassName.get("java.io", "InputStreamReader"), "ir", Modifier.PRIVATE) 251 | .addField(ClassName.get("java.io", "BufferedReader"), "br", Modifier.PRIVATE) 252 | .addField(ClassName.get("java.io", "OutputStreamWriter"), "osw", Modifier.PRIVATE) 253 | .addField(ClassName.get("android.content", "Context"), "context", Modifier.PRIVATE) 254 | .addField(ClassName.get("com.google.gson", "Gson"), "gson", Modifier.PRIVATE) 255 | .addMethod(loadMethod) 256 | .addMethod(saveMethod) 257 | .addMethod(generateContextConstructor()) 258 | .build(); 259 | 260 | // Write file 261 | JavaFile file = JavaFile.builder(packageName, manager).build(); 262 | file.writeTo(filer); 263 | } 264 | 265 | private static MethodSpec generateContextConstructor() { 266 | return MethodSpec.constructorBuilder() 267 | .addModifiers(Modifier.PUBLIC) 268 | .addParameter(ClassName.get("android.content", "Context"), "context") 269 | .addStatement("this.$N = $N", "context", "context") 270 | .build(); 271 | } 272 | 273 | } 274 | --------------------------------------------------------------------------------