Search in sources :

Example 96 with PackageElement

use of javax.lang.model.element.PackageElement in project kripton by xcesco.

the class BindSharedPreferencesBuilder method generate.

/**
 * Generate shared preference manager
 *
 * @return typeName of generated class
 *
 * @throws IOException
 */
public static String generate(Elements elementUtils, Filer filer, PrefsEntity entity) throws IOException {
    com.abubusoft.kripton.common.Converter<String, String> converter = CaseFormat.UPPER_CAMEL.converterTo(CaseFormat.LOWER_CAMEL);
    String beanClassName = entity.getSimpleName().toString();
    String suffix;
    if (beanClassName.endsWith(SUFFIX_SHARED_PREFERENCE)) {
        suffix = "";
    } else if (beanClassName.endsWith(SUFFIX_PREFERENCE)) {
        suffix = "";
    } else {
        suffix = SUFFIX_SHARED_PREFERENCE;
    }
    String className = PREFIX + beanClassName + suffix;
    ModelAnnotation annotation = entity.getAnnotation(BindSharedPreferences.class);
    String sharedPreferenceName = annotation.getAttribute(AnnotationAttributeType.VALUE);
    PackageElement pkg = elementUtils.getPackageOf(entity.getElement());
    String packageName = pkg.isUnnamed() ? "" : pkg.getQualifiedName().toString();
    AnnotationProcessorUtilis.infoOnGeneratedClasses(BindSharedPreferences.class, packageName, className);
    // @formatter:off
    builder = TypeSpec.classBuilder(className).addModifiers(Modifier.PUBLIC).superclass(AbstractSharedPreference.class);
    BindTypeContext context = new BindTypeContext(builder, TypeUtility.typeName(entity.getElement()), Modifier.PRIVATE);
    // @formatter:on
    builder.addJavadoc("This class is the shared preference binder defined for $T\n\n", entity.getElement());
    JavadocUtility.generateJavadocGeneratedBy(builder);
    builder.addJavadoc("@see $T\n", entity.getElement());
    if (StringUtils.hasText(sharedPreferenceName)) {
        builder.addField(FieldSpec.builder(String.class, "SHARED_PREFERENCE_NAME", Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL).initializer("$S", converter.convert(entity.getSimpleName().toString())).addJavadoc("shared preferences typeName for $T\n", entity.getElement()).build());
    }
    builder.addField(FieldSpec.builder(className(beanClassName), "defaultBean", Modifier.PRIVATE, Modifier.FINAL).addJavadoc("working instance of bean\n").build());
    {
        MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("edit").addJavadoc("create an editor to modify shared preferences\n").returns(typeName("BindEditor")).addModifiers(Modifier.PUBLIC);
        methodBuilder.addStatement("return new $T()", typeName("BindEditor"));
        builder.addMethod(methodBuilder.build());
    }
    generateEditor(entity);
    generateConstructor(sharedPreferenceName, beanClassName);
    generateRefresh(sharedPreferenceName, className);
    generateResetMethod(entity);
    generateReadMethod(entity);
    generateWriteMethod(entity);
    generateSingleReadMethod(entity);
    // generate all needed writer and reader
    List<PrefsProperty> fields = entity.getCollection();
    List<PrefsProperty> filteredFields = new ArrayList<>();
    // we need to avoid generation of persists values
    for (PrefsProperty item : fields) {
        if (SetPrefsTransformation.isStringSet(item)) {
            continue;
        } else {
            filteredFields.add(item);
        }
    }
    // avoid to consider StringSet
    ManagedPropertyPersistenceHelper.generateFieldPersistance(context, filteredFields, PersistType.STRING, false, Modifier.PROTECTED);
    generateInstance(className);
    TypeSpec typeSpec = builder.build();
    JavaWriterHelper.writeJava2File(filer, packageName, typeSpec);
    return className;
}
Also used : Builder(com.squareup.javapoet.TypeSpec.Builder) ArrayList(java.util.ArrayList) BindTypeContext(com.abubusoft.kripton.processor.bind.BindTypeContext) AbstractSharedPreference(com.abubusoft.kripton.android.sharedprefs.AbstractSharedPreference) ModelAnnotation(com.abubusoft.kripton.processor.core.ModelAnnotation) PrefsProperty(com.abubusoft.kripton.processor.sharedprefs.model.PrefsProperty) PackageElement(javax.lang.model.element.PackageElement) TypeSpec(com.squareup.javapoet.TypeSpec)

Example 97 with PackageElement

use of javax.lang.model.element.PackageElement in project kripton by xcesco.

the class BindTableGenerator method visit.

@Override
public void visit(SQLiteDatabaseSchema schema, SQLiteEntity entity) throws Exception {
    int indexCounter = 0;
    // generate the class name that represents the table
    String classTableName = getTableClassName(entity.getSimpleName());
    PackageElement pkg = elementUtils.getPackageOf(entity.getElement());
    String packageName = pkg.isUnnamed() ? null : pkg.getQualifiedName().toString();
    AnnotationProcessorUtilis.infoOnGeneratedClasses(BindDataSource.class, packageName, classTableName);
    classBuilder = TypeSpec.classBuilder(classTableName).addModifiers(Modifier.PUBLIC).addSuperinterface(SQLiteTable.class);
    BindTypeContext context = new BindTypeContext(classBuilder, TypeUtility.typeName(packageName, classTableName), Modifier.STATIC, Modifier.PRIVATE);
    // javadoc for class
    classBuilder.addJavadoc("<p>");
    classBuilder.addJavadoc("\nEntity <code>$L</code> is associated to table <code>$L</code>\n", entity.getSimpleName(), entity.getTableName());
    classBuilder.addJavadoc("This class represents table associated to entity.\n");
    classBuilder.addJavadoc("</p>\n");
    JavadocUtility.generateJavadocGeneratedBy(classBuilder);
    classBuilder.addJavadoc(" @see $T\n", TypeUtility.className(entity.getName()));
    {
        // @formatter:off
        // table_name
        FieldSpec fieldSpec = FieldSpec.builder(String.class, "TABLE_NAME", Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL).initializer("\"$L\"", entity.getTableName()).addJavadoc("Costant represents typeName of table $L\n", entity.getTableName()).build();
        classBuilder.addField(fieldSpec);
    // @formatter:on
    }
    StringBuilder bufferTable = new StringBuilder();
    StringBuilder bufferForeignKey = new StringBuilder();
    // shared between create table and drop table
    StringBuilder bufferIndexesCreate = new StringBuilder();
    StringBuilder bufferDropTable = new StringBuilder();
    StringBuilder bufferIndexesDrop = new StringBuilder();
    bufferTable.append("CREATE TABLE " + entity.getTableName());
    // define column typeName set
    String separator = "";
    bufferTable.append(" (");
    // for each column, that need to be persisted on table
    for (SQLProperty item : entity.getCollection()) {
        bufferTable.append(separator);
        bufferTable.append(item.columnName);
        bufferTable.append(" " + SQLTransformer.columnTypeAsString(item));
        switch(item.columnType) {
            case PRIMARY_KEY:
                bufferTable.append(" PRIMARY KEY AUTOINCREMENT");
                break;
            case UNIQUE:
                bufferTable.append(" UNIQUE");
                break;
            case INDEXED:
                bufferIndexesCreate.append(String.format(" CREATE INDEX idx_%s_%s ON %s(%s);", entity.getTableName(), item.columnName, entity.getTableName(), item.columnName));
                bufferIndexesDrop.append(String.format(" DROP INDEX IF EXISTS idx_%s_%s;", entity.getTableName(), item.columnName));
                break;
            case STANDARD:
                break;
        }
        boolean nullable = item.isNullable();
        // null
        if (!nullable && item.columnType != ColumnType.PRIMARY_KEY) {
            bufferTable.append(" NOT NULL");
        }
        // foreign key
        String foreignClassName = item.foreignClassName;
        if (item.hasForeignKeyClassName()) {
            SQLiteEntity reference = model.getEntity(foreignClassName);
            if (reference == null) {
                // check if we have a DAO associated into DataSource
                // definition
                boolean found = false;
                for (SQLiteDaoDefinition daoDefinition : schema.getCollection()) {
                    if (daoDefinition.getEntityClassName().equals(foreignClassName)) {
                        found = true;
                    }
                }
                if (!found) {
                    throw new NoDaoElementFound(schema, TypeUtility.className(foreignClassName));
                } else {
                    throw new InvalidBeanTypeException(item, foreignClassName);
                }
            }
            // long/Long
            if (!TypeUtility.isTypeIncludedIn(item.getPropertyType().getTypeName(), Long.class, Long.TYPE)) {
                throw new InvalidForeignKeyTypeException(item);
            }
            bufferForeignKey.append(", FOREIGN KEY(" + item.columnName + ") REFERENCES " + reference.getTableName() + "(" + reference.getPrimaryKey().columnName + ")");
            if (item.onDeleteAction != ForeignKeyAction.NO_ACTION) {
                bufferForeignKey.append(" ON DELETE " + item.onDeleteAction.toString().replaceAll("_", " "));
            }
            if (item.onUpdateAction != ForeignKeyAction.NO_ACTION) {
                bufferForeignKey.append(" ON UPDATE " + item.onUpdateAction.toString().replaceAll("_", " "));
            }
            // Same entity can not be own dependency.
            if (!entity.equals(reference)) {
                entity.referedEntities.add(reference);
            }
        }
        separator = ", ";
    }
    // add foreign key
    bufferTable.append(bufferForeignKey.toString());
    bufferTable.append(");");
    // add indexes creation one table
    if (bufferIndexesCreate.length() > 0) {
        bufferTable.append(bufferIndexesCreate.toString());
    }
    // add multicolumn indexes (UNIQUE)
    {
        Pair<String, String> multiIndexes = buldIndexes(entity, true, indexCounter);
        if (!StringUtils.isEmpty(multiIndexes.value0)) {
            bufferTable.append(multiIndexes.value0 + ";");
            bufferIndexesDrop.append(multiIndexes.value1 + ";");
        }
    }
    // add multicolumn indexes (NOT UNIQUE)
    {
        Pair<String, String> multiIndexes = buldIndexes(entity, false, indexCounter);
        if (!StringUtils.isEmpty(multiIndexes.value0)) {
            bufferTable.append(multiIndexes.value0 + ";");
            bufferIndexesDrop.append(multiIndexes.value1 + ";");
        }
    }
    {
        // create table SQL
        // @formatter:off
        FieldSpec.Builder fieldSpec = FieldSpec.builder(String.class, "CREATE_TABLE_SQL").addModifiers(Modifier.STATIC, Modifier.FINAL, Modifier.PUBLIC);
        // @formatter:on
        // @formatter:off
        fieldSpec.addJavadoc("<p>\nDDL to create table $L\n</p>\n", entity.getTableName());
        fieldSpec.addJavadoc("\n<pre>$L</pre>\n", bufferTable.toString());
        // @formatter:on
        classBuilder.addField(fieldSpec.initializer("$S", bufferTable.toString()).build());
    }
    // with tables
    if (bufferIndexesDrop.length() > 0) {
        bufferDropTable.append(bufferIndexesDrop.toString());
    }
    bufferDropTable.append("DROP TABLE IF EXISTS " + entity.getTableName() + ";");
    {
        // @formatter:off
        FieldSpec fieldSpec = FieldSpec.builder(String.class, "DROP_TABLE_SQL").addModifiers(Modifier.STATIC, Modifier.FINAL, Modifier.PUBLIC).initializer("$S", bufferDropTable.toString()).addJavadoc("<p>\nDDL to drop table $L\n</p>\n", entity.getTableName()).addJavadoc("\n<pre>$L</pre>\n", bufferDropTable.toString()).build();
        // @formatter:on
        classBuilder.addField(fieldSpec);
    }
    // define column typeName set
    for (ModelProperty item : entity.getCollection()) {
        item.accept(this);
    }
    ManagedPropertyPersistenceHelper.generateFieldPersistance(context, entity.getCollection(), PersistType.BYTE, true, Modifier.STATIC, Modifier.PUBLIC);
    model.sqlForCreate.add(bufferTable.toString());
    model.sqlForDrop.add(bufferDropTable.toString());
    generateColumnsArray(entity);
    TypeSpec typeSpec = classBuilder.build();
    JavaWriterHelper.writeJava2File(filer, packageName, typeSpec);
}
Also used : InvalidForeignKeyTypeException(com.abubusoft.kripton.processor.exceptions.InvalidForeignKeyTypeException) Builder(com.squareup.javapoet.FieldSpec.Builder) InvalidBeanTypeException(com.abubusoft.kripton.processor.exceptions.InvalidBeanTypeException) SQLiteTable(com.abubusoft.kripton.android.sqlite.SQLiteTable) BindTypeContext(com.abubusoft.kripton.processor.bind.BindTypeContext) FieldSpec(com.squareup.javapoet.FieldSpec) SQLiteDaoDefinition(com.abubusoft.kripton.processor.sqlite.model.SQLiteDaoDefinition) NoDaoElementFound(com.abubusoft.kripton.processor.exceptions.NoDaoElementFound) SQLProperty(com.abubusoft.kripton.processor.sqlite.model.SQLProperty) ModelProperty(com.abubusoft.kripton.processor.core.ModelProperty) PackageElement(javax.lang.model.element.PackageElement) SQLiteEntity(com.abubusoft.kripton.processor.sqlite.model.SQLiteEntity) Pair(com.abubusoft.kripton.common.Pair) TypeSpec(com.squareup.javapoet.TypeSpec)

Example 98 with PackageElement

use of javax.lang.model.element.PackageElement in project kripton by xcesco.

the class BindAsyncTaskBuilder method generate.

/**
 * Generate async task for database operations
 *
 * @throws IOException
 */
public static void generate(Elements elementUtils, Filer filer, SQLiteDatabaseSchema schema) throws IOException {
    String className = schema.getName();
    String dataSourceName = PREFIX + className;
    className = className.replaceAll(BindDataSourceBuilder.SUFFIX, SUFFIX);
    className = PREFIX + className;
    PackageElement pkg = elementUtils.getPackageOf(schema.getElement());
    String packageName = pkg.isUnnamed() ? "" : pkg.getQualifiedName().toString();
    AnnotationProcessorUtilis.infoOnGeneratedClasses(BindDataSource.class, packageName, className);
    // @formatter:off
    builder = TypeSpec.classBuilder(className).addModifiers(Modifier.PUBLIC).addModifiers(Modifier.ABSTRACT).addTypeVariable(TypeVariableName.get("I")).addTypeVariable(TypeVariableName.get("U")).addTypeVariable(TypeVariableName.get("R"));
    // @formatter:on
    // javadoc
    builder.addJavadoc("\n<p>\nSpecialized async task to make async database operation on activity\n</p>\n");
    builder.addJavadoc("\n<p>\nUnlike standard async task, for an instance of this class can be used many time.\n</p>\n");
    builder.addJavadoc("\n<p>\nWhen method <code>execute</code> is invoked, an inner async task is created.\n</p>\n\n");
    JavadocUtility.generateJavadocGeneratedBy(builder);
    builder.addJavadoc("@param I input param\n");
    builder.addJavadoc("@param U update param\n");
    builder.addJavadoc("@param R result param\n\n");
    builder.addJavadoc("@see $T\n", className(className.replaceAll(SUFFIX, BindDaoFactoryBuilder.SUFFIX)));
    builder.addJavadoc("@see $T\n", className(dataSourceName));
    builder.addJavadoc("@see $T\n", BindAsyncTaskType.class);
    // build constructors
    builder.addMethod(MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC).addStatement("this($T.READ)", BindAsyncTaskType.class).addJavadoc("<p>\nWith this constructor, a read only database connection will be used\n</p>\n").build());
    builder.addMethod(MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC).addJavadoc("<p>\nWith this constructor it is possible to specify which type of database use in async task\n</p>\n\n").addJavadoc("@param mode allows to specify if and how open a data source connection\n").addParameter(BindAsyncTaskType.class, "mode").addCode("this.mode = mode;").build());
    // define fields
    {
        FieldSpec.Builder fieldSpec = FieldSpec.builder(BindAsyncTaskType.class, "mode", Modifier.PROTECTED);
        fieldSpec.addJavadoc("Allows to specify how async task interacts with data source.\n\n");
        builder.addField(fieldSpec.build());
    }
    {
        ParameterizedTypeName parameterizedTypeName = ParameterizedTypeName.get(TypeUtility.className(AsyncTask.class), TypeUtility.typeName("I"), TypeUtility.typeName("U"), TypeUtility.typeName("R"));
        FieldSpec.Builder fieldSpec = FieldSpec.builder(parameterizedTypeName, "asyncTask", Modifier.PROTECTED);
        fieldSpec.addJavadoc("Async task wrapped by this class\n\n");
        builder.addField(fieldSpec.build());
    }
    // build methods
    builder.addMethod(MethodSpec.methodBuilder("onPreExecute").addModifiers(Modifier.PUBLIC).addJavadoc("Use this method for operations on UI-thread before start execution\n").build());
    builder.addMethod(MethodSpec.methodBuilder("onExecute").returns(TypeUtility.typeName("R")).addParameter(TypeUtility.typeName(dataSourceName), "dataSource").addJavadoc("Method used to encapsulate operations on datasource\n\n@param dataSource\n\tuse it to retrieve DAO\n@return\n\tresult of operation (list, bean, etc) and execute transactions.\n").addModifiers(Modifier.PUBLIC).addModifiers(Modifier.ABSTRACT).addException(Throwable.class).build());
    builder.addMethod(MethodSpec.methodBuilder("onFinish").addParameter(TypeUtility.typeName("R"), "result").addModifiers(Modifier.PUBLIC).addModifiers(Modifier.ABSTRACT).addJavadoc("Use this method for operations on UI-thread after execution\n").build());
    builder.addMethod(MethodSpec.methodBuilder("onProgressUpdate").addModifiers(Modifier.PUBLIC).addParameter(ParameterSpec.builder(ArrayTypeName.of(TypeUtility.typeName("U")), "update").build()).varargs().addJavadoc("Override this method to KRIPTON_DEBUG operation progress on UI-Thread\n").build());
    builder.addMethod(MethodSpec.methodBuilder("onError").addParameter(Throwable.class, "exception").addModifiers(Modifier.PUBLIC).addJavadoc("This method is invoked when <code>onExecute</code> method generate an exception.\n@param exception exception generated\n").addStatement("$T.error(exception.getMessage())", Logger.class).addStatement("exception.printStackTrace()").build());
    // method execute1
    {
        MethodSpec.Builder executeBuilder = MethodSpec.methodBuilder("execute").addParameter(ParameterSpec.builder(ArrayTypeName.of(TypeUtility.className("I")), "params").addAnnotation(AnnotationSpec.builder(SuppressWarnings.class).addMember("value", "$S", "unchecked").build()).build()).varargs(true).addModifiers(Modifier.PUBLIC).addJavadoc("Method to start operations.\n\n@param executor used executor\n@param data input\n");
        executeBuilder.addStatement("executeOnExecutor($T.SERIAL_EXECUTOR, params)", android.os.AsyncTask.class);
        builder.addMethod(executeBuilder.build());
    }
    // method execute2
    {
        MethodSpec.Builder executeBuilder = MethodSpec.methodBuilder("executeOnExecutor").addParameter(Executor.class, "executor").addParameter(ParameterSpec.builder(ArrayTypeName.of(TypeUtility.className("I")), "params").addAnnotation(AnnotationSpec.builder(SuppressWarnings.class).addMember("value", "$S", "unchecked").build()).build()).varargs(true).addModifiers(Modifier.PUBLIC).addJavadoc("Method to start operations.\n\n@param executor used executor\n@param data input\n");
        // @formatter:off
        TypeSpec.Builder anonymous = TypeSpec.anonymousClassBuilder("").addSuperinterface(ParameterizedTypeName.get(TypeUtility.className(AsyncTask.class), TypeUtility.className("I"), TypeUtility.className("U"), TypeUtility.className("R")));
        anonymous.addMethod(MethodSpec.methodBuilder("onPreExecute").addModifiers(Modifier.PUBLIC).addAnnotation(Override.class).addStatement("$L.this.onPreExecute()", className).build());
        anonymous.addMethod(MethodSpec.methodBuilder("doInBackground").addModifiers(Modifier.PUBLIC).returns(TypeUtility.typeName("R")).addAnnotation(Override.class).addParameter(ParameterSpec.builder(ArrayTypeName.of(TypeUtility.className("I")), "params").addAnnotation(AnnotationSpec.builder(SuppressWarnings.class).addMember("value", "$S", "unchecked").build()).build()).varargs(true).addStatement("$L dataSource=$L.instance()", dataSourceName, dataSourceName).addStatement("R result=null").addStatement("if (mode==$T.READ) dataSource.openReadOnlyDatabase(); else if (mode==$T.READ_WRITE) dataSource.openWritableDatabase()", BindAsyncTaskType.class, BindAsyncTaskType.class).beginControlFlow("try").addStatement("result=onExecute(dataSource)").nextControlFlow("catch(Throwable e)").addStatement("onError(e)").nextControlFlow("finally").beginControlFlow("if (dataSource.isOpen())").addStatement("dataSource.close()").endControlFlow().endControlFlow().addStatement("return result").build());
        anonymous.addMethod(MethodSpec.methodBuilder("onProgressUpdate").addModifiers(Modifier.PUBLIC).addAnnotation(Override.class).addParameter(ParameterSpec.builder(ArrayTypeName.of(TypeUtility.className("U")), "values").addAnnotation(AnnotationSpec.builder(SuppressWarnings.class).addMember("value", "$S", "unchecked").build()).build()).varargs(true).addStatement("$L.this.onProgressUpdate(values)", className).build());
        anonymous.addMethod(MethodSpec.methodBuilder("onPostExecute").addModifiers(Modifier.PUBLIC).addAnnotation(Override.class).addParameter(ParameterSpec.builder(TypeUtility.className("R"), "result").build()).addStatement("$L.this.onFinish(result)", className).build());
        // @formatter:on
        // @formatter:off
        executeBuilder.addStatement("asyncTask=$L", anonymous.build());
        executeBuilder.addStatement("asyncTask.executeOnExecutor(executor, params)", anonymous.build());
        builder.addMethod(executeBuilder.build());
        anonymous.addMethod(MethodSpec.methodBuilder("cancel").addModifiers(Modifier.PUBLIC).addModifiers(Modifier.FINAL).addParameter(Boolean.TYPE, "mayInterruptIfRunning").beginControlFlow("if (asyncTask!=null, args)").addStatement("return asyncTask.cancel(mayInterruptIfRunning)").endControlFlow().addStatement("return false").build());
    }
    // build SimpleAsyncTask
    builder.addType(TypeSpec.classBuilder("Simple").addJavadoc("Simple implementation of async task. It uses read only database.\n\n").addJavadoc("@see $T\n", TypeUtility.typeName(className.replaceAll(SUFFIX, BindDaoFactoryBuilder.SUFFIX))).addJavadoc("@see $T\n", TypeUtility.typeName(dataSourceName)).addModifiers(Modifier.PUBLIC).addModifiers(Modifier.STATIC).addModifiers(Modifier.ABSTRACT).addTypeVariable(TypeVariableName.get("R")).superclass(ParameterizedTypeName.get(TypeUtility.className(className), TypeUtility.className("Void"), TypeUtility.className("Void"), TypeUtility.className("R"))).addMethod(MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC).addJavadoc("Create an simple async task allowing user to decide which kind of operation can be done on datasource").addParameter(BindAsyncTaskType.class, "mode").addStatement("super(mode)").build()).addMethod(MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC).addJavadoc("Create an simple async task for data source read only operation").addStatement("super($T.READ)", BindAsyncTaskType.class).build()).build());
    // @formatter:on
    TypeSpec typeSpec = builder.build();
    JavaWriterHelper.writeJava2File(filer, packageName, typeSpec);
}
Also used : Executor(java.util.concurrent.Executor) Builder(com.squareup.javapoet.TypeSpec.Builder) AsyncTask(android.os.AsyncTask) PackageElement(javax.lang.model.element.PackageElement) Logger(com.abubusoft.kripton.android.Logger) BindAsyncTaskType(com.abubusoft.kripton.android.BindAsyncTaskType) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) TypeSpec(com.squareup.javapoet.TypeSpec)

Example 99 with PackageElement

use of javax.lang.model.element.PackageElement in project kripton by xcesco.

the class BindCursorBuilder method visit.

@Override
public void visit(SQLiteDatabaseSchema schema, SQLiteEntity entity) throws Exception {
    String classCursorName = PREFIX + entity.getSimpleName() + SUFFIX;
    PackageElement pkg = elementUtils.getPackageOf(entity.getElement());
    String packageName = pkg.isUnnamed() ? "" : pkg.getQualifiedName().toString();
    ClassName className = TypeUtility.className(packageName, classCursorName);
    AnnotationProcessorUtilis.infoOnGeneratedClasses(BindDataSource.class, packageName, classCursorName);
    classBuilder = TypeSpec.classBuilder(classCursorName).addModifiers(Modifier.PUBLIC);
    // javadoc for class
    classBuilder.addJavadoc("<p>");
    classBuilder.addJavadoc("\nCursor implementation for entity <code>$L</code>\n", entity.getSimpleName());
    classBuilder.addJavadoc("</p>\n");
    JavadocUtility.generateJavadocGeneratedBy(classBuilder);
    classBuilder.addJavadoc(" @see $T\n", TypeUtility.className(entity.getElement().getQualifiedName().toString()));
    // @formatter:off
    FieldSpec fieldSpec = FieldSpec.builder(Cursor.class, "cursor", Modifier.PROTECTED).addJavadoc("Cursor used to read database\n").build();
    // @formatter:on
    classBuilder.addField(fieldSpec);
    // add constructor
    // @formatter:off
    classBuilder.addMethod(MethodSpec.constructorBuilder().addJavadoc("<p>Constructor</p>\n\n").addJavadoc("@param cursor cursor used to read from database\n").addParameter(Cursor.class, "cursor").addCode("wrap(cursor);\n").build());
    // @formatter:on
    // add wrap method
    // @formatter:off
    MethodSpec.Builder wrapMethodBuilder = MethodSpec.methodBuilder("wrap").addJavadoc("<p>Wrap cursor with this class</p>\n\n").addJavadoc("@param cursor cursor to include\n").addModifiers(Modifier.PUBLIC).addParameter(Cursor.class, "cursor").returns(className).addCode("this.cursor=cursor;\n");
    // @formatter:on
    counter = 0;
    wrapMethodBuilder.addCode("\n");
    for (SQLProperty item : entity.getCollection()) {
        wrapMethodBuilder.addCode("index$L=cursor.getColumnIndex($S);\n", counter, item.columnName);
        counter++;
    }
    wrapMethodBuilder.addCode("\n");
    wrapMethodBuilder.addCode("return this;\n");
    classBuilder.addMethod(wrapMethodBuilder.build());
    // add execute method
    classBuilder.addMethod(generateExecuteMethod(packageName, entity).build());
    // add execute listener method
    classBuilder.addMethod(generateExecuteListener(packageName, entity).build());
    // add create
    // @formatter:off
    classBuilder.addMethod(MethodSpec.methodBuilder("create").addModifiers(Modifier.STATIC, Modifier.PUBLIC).addParameter(Cursor.class, "cursor").returns(className(packageName, classCursorName)).addJavadoc("<p>Create a binded cursor starting from a cursor</p>\n\n").addJavadoc("@param cursor to wrap\n").addCode("return new " + classCursorName + "(cursor);\n").build());
    // @formatter:on
    // define column typeName set
    counter = 0;
    for (ModelProperty item : entity.getCollection()) {
        item.accept(this);
    }
    TypeSpec typeSpec = classBuilder.build();
    JavaWriterHelper.writeJava2File(filer, packageName, typeSpec);
}
Also used : MethodSpec(com.squareup.javapoet.MethodSpec) ClassName(com.squareup.javapoet.ClassName) SQLProperty(com.abubusoft.kripton.processor.sqlite.model.SQLProperty) ModelProperty(com.abubusoft.kripton.processor.core.ModelProperty) PackageElement(javax.lang.model.element.PackageElement) Cursor(android.database.Cursor) FieldSpec(com.squareup.javapoet.FieldSpec) TypeSpec(com.squareup.javapoet.TypeSpec)

Example 100 with PackageElement

use of javax.lang.model.element.PackageElement in project kripton by xcesco.

the class BindDaoFactoryBuilder method buildDaoFactoryInterface.

/**
 * Build dao factory interface
 *
 * @param elementUtils
 * @param filer
 * @param schema
 *
 * @return schema typeName
 *
 * @throws Exception
 */
public String buildDaoFactoryInterface(Elements elementUtils, Filer filer, SQLiteDatabaseSchema schema) throws Exception {
    String schemaName = generateDaoFactoryName(schema);
    PackageElement pkg = elementUtils.getPackageOf(schema.getElement());
    String packageName = pkg.isUnnamed() ? "" : pkg.getQualifiedName().toString();
    AnnotationProcessorUtilis.infoOnGeneratedClasses(BindDataSource.class, packageName, schemaName);
    classBuilder = buildDaoFactoryInterfaceInternal(elementUtils, filer, schema);
    TypeSpec typeSpec = classBuilder.build();
    JavaWriterHelper.writeJava2File(filer, packageName, typeSpec);
    return schemaName;
}
Also used : PackageElement(javax.lang.model.element.PackageElement) TypeSpec(com.squareup.javapoet.TypeSpec)

Aggregations

PackageElement (javax.lang.model.element.PackageElement)134 TypeElement (javax.lang.model.element.TypeElement)93 Element (javax.lang.model.element.Element)52 ExecutableElement (javax.lang.model.element.ExecutableElement)34 VariableElement (javax.lang.model.element.VariableElement)32 TypeSpec (com.squareup.javapoet.TypeSpec)20 IOException (java.io.IOException)17 HashSet (java.util.HashSet)13 TypeMirror (javax.lang.model.type.TypeMirror)13 AnnotationMirror (javax.lang.model.element.AnnotationMirror)12 JavaFileObject (javax.tools.JavaFileObject)12 ClassName (com.squareup.javapoet.ClassName)11 ArrayList (java.util.ArrayList)11 Set (java.util.Set)10 Elements (javax.lang.model.util.Elements)10 PrintWriter (java.io.PrintWriter)9 HashMap (java.util.HashMap)9 ParameterizedTypeName (com.squareup.javapoet.ParameterizedTypeName)8 Map (java.util.Map)8 Messager (javax.annotation.processing.Messager)8