Search in sources :

Example 31 with PackageElement

use of javax.lang.model.element.PackageElement in project ucsFramework by cjsoftware-lib.

the class PreserveUiStateProcessor method completeProcessing.

@Override
protected void completeProcessing() {
    super.completeProcessing();
    if (isFatalErrorEncountered()) {
        // If we hit a fatal error, bail.
        return;
    }
    for (TypeElement preservedFieldContainer : preservedFieldGroups.keySet()) {
        PackageElement packageElement = getProcessorModel().getElementUtils().getPackageOf(preservedFieldContainer);
        ClassName generatedFieldListClassName = ClassName.get(packageElement.getQualifiedName().toString(), String.format(GENERATED_PRESERVED_FIELD_LIST_CLASS_NAME_TEMPLATE, sanitiseClassName(preservedFieldContainer.getSimpleName().toString())));
        TypeSpec.Builder preserveStateClass = TypeSpec.classBuilder(generatedFieldListClassName).addSuperinterface(ParameterizedTypeName.get(ClassName.get(StatePreservationManager.class), ClassName.get(preservedFieldContainer.asType()))).addField(FieldSpec.builder(TypeName.BOOLEAN, FIELD_HAVE_STATE).initializer("false").build());
        List<DoPreservedField> preservedFieldList = preservedFieldGroups.get(preservedFieldContainer);
        addStrategyFields(preserveStateClass, preservedFieldList, preservedFieldContainer.asType());
        preserveStateClass.addMethod(addSaveMethod(TypeName.get(preservedFieldContainer.asType()), preservedFieldList));
        for (DoPreservedField field : preservedFieldList) {
            preserveStateClass.addMethod(addSaveFieldMethod(TypeName.get(preservedFieldContainer.asType()), field));
        }
        preserveStateClass.addMethod(addRestoreMethod(TypeName.get(preservedFieldContainer.asType()), preservedFieldList));
        for (DoPreservedField field : preservedFieldList) {
            preserveStateClass.addMethod(addRestoreFieldMethod(TypeName.get(preservedFieldContainer.asType()), field));
        }
        try {
            JavaFile javaFile = JavaFile.builder(packageElement.getQualifiedName().toString(), preserveStateClass.build()).addFileComment("Generated Code, do not modify.").build();
            javaFile.writeTo(getProcessorModel().getFiler());
        } catch (IOException e) {
            fatalErrorMessage("Exception writing java file: " + e.toString(), preservedFieldContainer);
        }
    }
}
Also used : DoPreservedField(com.cjsoftware.processor.uistatepreservation.model.DoPreservedField) TypeElement(javax.lang.model.element.TypeElement) ClassName(com.squareup.javapoet.ClassName) StatePreservationManager(com.cjsoftware.library.uistatepreservation.StatePreservationManager) JavaFile(com.squareup.javapoet.JavaFile) PackageElement(javax.lang.model.element.PackageElement) IOException(java.io.IOException) TypeSpec(com.squareup.javapoet.TypeSpec)

Example 32 with PackageElement

use of javax.lang.model.element.PackageElement in project ucsFramework by cjsoftware-lib.

the class UcsContractProcessor method processElement.

@Override
public void processElement(TypeElement contractSpec) {
    PackageElement packageElement = getProcessorModel().getElementUtils().getPackageOf(contractSpec);
    ClassName generatedContractBrokerClassName = ClassName.get(packageElement.getQualifiedName().toString(), String.format(GENERATED_CONTRACT_BROKER_CLASS_NAME_TEMPLATE, sanitiseClassName(contractSpec.getSimpleName().toString())));
    String qualifiedPackageName = packageElement.getQualifiedName().toString();
    TypeElement uiContract = findDescendentOf(contractSpec, BaseUiContract.class);
    ClassName uiProxyQueueClass = null;
    if (uiContract != null) {
        ProxyQueueBuilder uiProxyQueueBuilder = new ProxyQueueBuilder(getProcessorModel(), qualifiedPackageName, false, true);
        uiProxyQueueClass = uiProxyQueueBuilder.buildClass(uiContract);
    }
    TypeElement coordinatorContract = findDescendentOf(contractSpec, BaseCoordinatorContract.class);
    ClassName coordinatorProxyQueueClass = null;
    if (coordinatorContract != null) {
        ProxyQueueBuilder coordinatorProxyQueueBuilder = new ProxyQueueBuilder(getProcessorModel(), qualifiedPackageName, true, true);
        coordinatorProxyQueueClass = coordinatorProxyQueueBuilder.buildClass(coordinatorContract);
    }
    TypeElement screenNavigationContract = findDescendentOf(contractSpec, BaseScreenNavigationContract.class);
    ClassName screenNavigationProxyQueueClass = null;
    if (screenNavigationContract != null) {
        ProxyQueueBuilder screenNavigationProxyQueueBuilder = new ProxyQueueBuilder(getProcessorModel(), qualifiedPackageName, false, true);
        screenNavigationProxyQueueClass = screenNavigationProxyQueueBuilder.buildClass(screenNavigationContract);
    }
    TypeElement stateManagerContract = findDescendentOf(contractSpec, BaseStateManagerContract.class);
    ParameterizedTypeName contractBrokerSuperInterface = ParameterizedTypeName.get(ClassName.get(ContractBroker.class), ClassName.get(uiContract), ClassName.get(screenNavigationContract), ClassName.get(coordinatorContract), ClassName.get(stateManagerContract));
    TypeSpec.Builder contractBrokerClass = TypeSpec.classBuilder(generatedContractBrokerClassName).addModifiers(Modifier.PUBLIC).addSuperinterface(contractBrokerSuperInterface);
    contractBrokerClass.addField(TypeName.get(CoordinatorBinder.class), PROXY_BINDER_FIELD_NAME, Modifier.PRIVATE);
    contractBrokerClass.addField(TypeName.get(coordinatorContract.asType()), COORDINATOR_FIELD_NAME, Modifier.PRIVATE);
    contractBrokerClass.addField(TypeName.get(stateManagerContract.asType()), STATEMANAGER_FIELD_NAME, Modifier.PRIVATE);
    contractBrokerClass.addField(coordinatorProxyQueueClass, COORDINATOR_PROXY_QUEUE_FIELD_NAME, Modifier.PRIVATE);
    contractBrokerClass.addField(uiProxyQueueClass, UI_PROXY_QUEUE_FIELD_NAME, Modifier.PRIVATE);
    contractBrokerClass.addField(screenNavigationProxyQueueClass, SCREEN_NAVIGATION_PROXY_QUEUE_FIELD_NAME, Modifier.PRIVATE);
    TypeSpec coordinatorBinderProxy = buildBindingProxyClass(uiContract, screenNavigationContract, stateManagerContract);
    contractBrokerClass.addType(coordinatorBinderProxy);
    contractBrokerClass.addMethod(MethodSpec.constructorBuilder().addAnnotation(ClassName.get("javax.inject", "Inject")).addModifiers(Modifier.PUBLIC).addParameter(ParameterSpec.builder(ClassName.get(Executor.class), "uiExecutor").addAnnotation(AnnotationSpec.builder(ClassName.get("com.cjsoftware.library.platform.android.dagger", "MainLooper")).build()).build()).addParameter(ClassName.get(Executor.class), "backgroundExecutor").addParameter(TypeName.get(coordinatorContract.asType()), COORDINATOR_PARAM_NAME).addParameter(TypeName.get(stateManagerContract.asType()), STATEMANAGER_PARAM_NAME).addStatement("this.$N = $N", COORDINATOR_FIELD_NAME, COORDINATOR_PARAM_NAME).addStatement("this.$N = $N", STATEMANAGER_FIELD_NAME, STATEMANAGER_PARAM_NAME).addStatement("$N = new $T($N)", COORDINATOR_PROXY_QUEUE_FIELD_NAME, coordinatorProxyQueueClass, "backgroundExecutor").addStatement("$N.setProxiedInterface($N)", COORDINATOR_PROXY_QUEUE_FIELD_NAME, COORDINATOR_PARAM_NAME).addStatement("this.$N = new $T($N)", UI_PROXY_QUEUE_FIELD_NAME, uiProxyQueueClass, "uiExecutor").addStatement("this.$N = new $T($N)", SCREEN_NAVIGATION_PROXY_QUEUE_FIELD_NAME, screenNavigationProxyQueueClass, "uiExecutor").addStatement("(($T)this.$N).bindUi($N)", CoordinatorBinder.class, COORDINATOR_FIELD_NAME, UI_PROXY_QUEUE_FIELD_NAME).addStatement("(($T)this.$N).bindScreenNavigation(($T)$N)", CoordinatorBinder.class, COORDINATOR_FIELD_NAME, screenNavigationContract, SCREEN_NAVIGATION_PROXY_QUEUE_FIELD_NAME).addStatement("(($T)this.$N).bindStateManager($N)", CoordinatorBinder.class, COORDINATOR_FIELD_NAME, STATEMANAGER_FIELD_NAME).addStatement("this.$N = new $N()", PROXY_BINDER_FIELD_NAME, coordinatorBinderProxy.name).build());
    contractBrokerClass.addMethod(MethodSpec.methodBuilder("getCoordinatorBinder").addAnnotation(Override.class).addAnnotation(getProcessorModel().getNonNullAnnotationClassName()).addModifiers(Modifier.PUBLIC).returns(TypeName.get(CoordinatorBinder.class)).addStatement("return $N", PROXY_BINDER_FIELD_NAME).build());
    contractBrokerClass.addMethod(MethodSpec.methodBuilder("getCoordinator").addAnnotation(Override.class).addAnnotation(getProcessorModel().getNonNullAnnotationClassName()).addModifiers(Modifier.PUBLIC).returns(TypeName.get(coordinatorContract.asType())).addStatement("return $N", COORDINATOR_PROXY_QUEUE_FIELD_NAME).build());
    contractBrokerClass.addMethod(MethodSpec.methodBuilder("getUi").addAnnotation(Override.class).addAnnotation(getProcessorModel().getNonNullAnnotationClassName()).addModifiers(Modifier.PUBLIC).returns(TypeName.get(uiContract.asType())).addStatement("return this.$N", UI_PROXY_QUEUE_FIELD_NAME).build());
    contractBrokerClass.addMethod(MethodSpec.methodBuilder("getScreenNavigation").addAnnotation(Override.class).addAnnotation(getProcessorModel().getNonNullAnnotationClassName()).addModifiers(Modifier.PUBLIC).returns(TypeName.get(screenNavigationContract.asType())).addStatement("return this.$N", SCREEN_NAVIGATION_PROXY_QUEUE_FIELD_NAME).build());
    contractBrokerClass.addMethod(MethodSpec.methodBuilder("getStateManager").addAnnotation(Override.class).addAnnotation(getProcessorModel().getNonNullAnnotationClassName()).addModifiers(Modifier.PUBLIC).returns(TypeName.get(stateManagerContract.asType())).addStatement("return this.$N", STATEMANAGER_FIELD_NAME).build());
    try {
        JavaFile javaFile = JavaFile.builder(packageElement.getQualifiedName().toString(), contractBrokerClass.build()).addFileComment("Generated Code, do not modify.").build();
        javaFile.writeTo(getProcessorModel().getFiler());
    } catch (IOException e) {
        fatalErrorMessage("Exception writing java file: " + e.toString(), contractSpec);
    }
}
Also used : TypeElement(javax.lang.model.element.TypeElement) IOException(java.io.IOException) Executor(java.util.concurrent.Executor) ClassName(com.squareup.javapoet.ClassName) ProxyQueueBuilder(com.cjsoftware.processor.ucs.builder.ProxyQueueBuilder) JavaFile(com.squareup.javapoet.JavaFile) PackageElement(javax.lang.model.element.PackageElement) ContractBroker(com.cjsoftware.library.ucs.ContractBroker) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) TypeSpec(com.squareup.javapoet.TypeSpec) CoordinatorBinder(com.cjsoftware.library.ucs.CoordinatorBinder)

Example 33 with PackageElement

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

the class M2MEntity method extractEntityManagedByDAO.

/**
 * Works with @BindDaoMany2Many and @BindDao to extract entity name.
 *
 * @param item
 * @return
 */
public static M2MEntity extractEntityManagedByDAO(TypeElement daoElement) {
    ClassName entity1 = null;
    ClassName entity2 = null;
    String prefixId = null;
    String tableName = null;
    String entityName = null;
    PackageElement pkg = null;
    String packageName = null;
    boolean needToCreate = true;
    boolean generatedMethods = true;
    if (daoElement.getAnnotation(BindDaoMany2Many.class) != null) {
        entity1 = TypeUtility.className(AnnotationUtility.extractAsClassName(daoElement, BindDaoMany2Many.class, AnnotationAttributeType.ENTITY_1));
        entity2 = TypeUtility.className(AnnotationUtility.extractAsClassName(daoElement, BindDaoMany2Many.class, AnnotationAttributeType.ENTITY_2));
        prefixId = AnnotationUtility.extractAsString(daoElement, BindDaoMany2Many.class, AnnotationAttributeType.ID_NAME);
        tableName = AnnotationUtility.extractAsString(daoElement, BindDaoMany2Many.class, AnnotationAttributeType.TABLE_NAME);
        generatedMethods = AnnotationUtility.extractAsBoolean(daoElement, BindDaoMany2Many.class, AnnotationAttributeType.METHODS);
        entityName = entity1.simpleName() + entity2.simpleName();
        pkg = BaseProcessor.elementUtils.getPackageOf(daoElement);
        packageName = pkg.isUnnamed() ? null : pkg.getQualifiedName().toString();
    }
    if (daoElement.getAnnotation(BindDao.class) != null) {
        // we have @BindDao
        String derived = AnnotationUtility.extractAsClassName(daoElement, BindDao.class, AnnotationAttributeType.VALUE);
        ClassName clazz = TypeUtility.className(derived);
        packageName = clazz.packageName();
        entityName = clazz.simpleName();
        String tableTemp = AnnotationUtility.extractAsClassName(daoElement, BindDao.class, AnnotationAttributeType.TABLE_NAME);
        if (StringUtils.hasText(tableTemp)) {
            tableName = tableTemp;
        }
        needToCreate = false;
    }
    M2MEntity entity = new M2MEntity(daoElement, packageName, entityName, TypeUtility.className(daoElement.asType().toString()), entity1, entity2, prefixId, tableName, needToCreate, generatedMethods);
    return entity;
}
Also used : BindDao(com.abubusoft.kripton.android.annotation.BindDao) BindDaoMany2Many(com.abubusoft.kripton.android.annotation.BindDaoMany2Many) ClassName(com.squareup.javapoet.ClassName) PackageElement(javax.lang.model.element.PackageElement)

Example 34 with PackageElement

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

the class BindTableGenerator method visit.

private void visit(SQLiteDatabaseSchema schema, GeneratedTypeElement entity) throws Exception {
    int indexCounter = 0;
    // generate the class name that represents the table
    String classTableName = getTableClassName(entity.getSimpleName());
    PackageElement pkg = elementUtils.getPackageElement(entity.packageName);
    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);
        // every column is a long
        bufferTable.append(" " + SQLTransformer.lookup(TypeName.LONG).getColumnTypeAsString());
        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);
                }
            }
            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.getClassName().equals(TypeUtility.typeName(reference.getElement()))) {
                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 single column 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 : 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 35 with PackageElement

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

the class BindDaoBuilder method visit.

@Override
public void visit(SQLiteDaoDefinition value) throws Exception {
    currentDaoDefinition = value;
    // check if we need to generate or not
    if (value.getElement().getAnnotation(BindDaoMany2Many.class) != null && value.getElement().getAnnotation(BindGeneratedDao.class) == null) {
        return;
    }
    String classTableName = daoName(value);
    PackageElement pkg = elementUtils.getPackageOf(value.getElement());
    String packageName = pkg.isUnnamed() ? "" : pkg.getQualifiedName().toString();
    AnnotationProcessorUtilis.infoOnGeneratedClasses(BindDao.class, packageName, classTableName);
    builder = TypeSpec.classBuilder(classTableName).superclass(Dao.class).addSuperinterface(typeName(value.getElement())).addModifiers(Modifier.PUBLIC);
    for (TypeName item : value.implementedInterface) {
        builder.addSuperinterface(item);
    }
    BindTypeContext context = new BindTypeContext(builder, TypeUtility.typeName(packageName, classTableName), Modifier.PRIVATE);
    String entityName = BindDataSourceSubProcessor.generateEntityName(value, value.getEntity());
    // javadoc for class
    builder.addJavadoc("<p>");
    builder.addJavadoc("\nDAO implementation for entity <code>$L</code>, based on interface <code>$L</code>\n", entityName, value.getElement().getSimpleName().toString());
    builder.addJavadoc("</p>\n\n");
    JavadocUtility.generateJavadocGeneratedBy(builder);
    builder.addJavadoc(" @see $T\n", TypeUtility.className(value.getEntityClassName()));
    builder.addJavadoc(" @see $T\n", TypeUtility.className(value.getElement().getQualifiedName().toString()));
    builder.addJavadoc(" @see $T\n", BindTableGenerator.tableClassName(value, value.getEntity()));
    {
        // constructor
        MethodSpec.Builder methodBuilder = MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC).addParameter(SQLContext.class, "context");
        methodBuilder.addStatement("super(context)");
        builder.addMethod(methodBuilder.build());
    }
    // define column typeName set
    for (SQLiteModelMethod item : value.getCollection()) {
        item.accept(this);
    }
    // generate live data support methods
    if (value.hasLiveData()) {
        // method sendEvent
        {
            MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(METHOD_NAME_REGISTRY_EVENT).addModifiers(Modifier.PROTECTED).addParameter(Integer.TYPE, "affectedRows");
            methodBuilder.beginControlFlow("if (affectedRows==0)");
            methodBuilder.addStatement("return");
            methodBuilder.endControlFlow();
            methodBuilder.beginControlFlow("if (_context.isInSession())");
            methodBuilder.addStatement("_context.registrySQLEvent($T.$L)", BindDataSourceBuilder.generateDataSourceName(value.getParent()), value.daoUidName);
            methodBuilder.nextControlFlow("else");
            methodBuilder.addStatement("invalidateLiveData()");
            methodBuilder.endControlFlow();
            builder.addMethod(methodBuilder.build());
        }
        // field liveDatas
        {
            FieldSpec.Builder liveDataBuilder = FieldSpec.builder(ParameterizedTypeName.get(ClassName.get(Collection.class), ParameterizedTypeName.get(ClassName.get(WeakReference.class), ParameterizedTypeName.get(ClassName.get(KriptonComputableLiveData.class), WildcardTypeName.subtypeOf(Object.class)))), "liveDatas").addModifiers(Modifier.STATIC).initializer(CodeBlock.builder().add("$T.synchronizedCollection(new $T())", Collections.class, ParameterizedTypeName.get(ClassName.get(HashSet.class), ParameterizedTypeName.get(ClassName.get(WeakReference.class), ParameterizedTypeName.get(ClassName.get(KriptonComputableLiveData.class), WildcardTypeName.subtypeOf(Object.class))))).build());
            builder.addField(liveDataBuilder.build());
        }
        // registryLiveData
        {
            MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(METHOD_NAME_REGISTRY_LIVE_DATA).addModifiers(Modifier.PROTECTED).addParameter(ParameterizedTypeName.get(ClassName.get(KriptonComputableLiveData.class), WildcardTypeName.subtypeOf(Object.class)), "value");
            methodBuilder.addStatement("liveDatas.add(new $T(value))", ParameterizedTypeName.get(ClassName.get(WeakReference.class), ParameterizedTypeName.get(ClassName.get(KriptonComputableLiveData.class), WildcardTypeName.subtypeOf(Object.class))));
            builder.addMethod(methodBuilder.build());
        }
        // invalidateLiveData
        {
            MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(METHOD_NAME_INVALIDATE_LIVE_DATA).addModifiers(Modifier.PROTECTED);
            methodBuilder.beginControlFlow("for ($T item: liveDatas)", ParameterizedTypeName.get(ClassName.get(WeakReference.class), ParameterizedTypeName.get(ClassName.get(KriptonComputableLiveData.class), WildcardTypeName.subtypeOf(Object.class))));
            methodBuilder.beginControlFlow("if (item.get()!=null)");
            methodBuilder.addStatement("item.get().invalidate()");
            methodBuilder.endControlFlow();
            methodBuilder.endControlFlow();
            builder.addMethod(methodBuilder.build());
        }
    }
    // generate serializer params
    for (Entry<TypeName, String> item : currentDaoDefinition.managedParams.entrySet()) {
        ManagedPropertyPersistenceHelper.generateParamSerializer(context, item.getValue(), item.getKey(), PersistType.BYTE);
        ManagedPropertyPersistenceHelper.generateParamParser(context, item.getValue(), item.getKey(), PersistType.BYTE);
    }
    // generate subject
    if (currentDaoDefinition.getParent().generateRx) {
        ParameterizedTypeName subjectTypeName = ParameterizedTypeName.get(ClassName.get(PublishSubject.class), ClassName.get(SQLiteEvent.class));
        // subject
        MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("subject").addModifiers(Modifier.PUBLIC);
        methodBuilder.addStatement("return subject").returns(subjectTypeName);
        builder.addMethod(methodBuilder.build());
        // subject instance
        FieldSpec.Builder fieldBuilder = FieldSpec.builder(subjectTypeName, "subject", Modifier.PRIVATE, Modifier.FINAL, Modifier.STATIC).initializer("$T.create()", ClassName.get(PublishSubject.class));
        builder.addField(fieldBuilder.build());
    }
    // generate prepared statement cleaner
    {
        MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("clearCompiledStatements").addModifiers(Modifier.PUBLIC, Modifier.STATIC).returns(Void.TYPE);
        for (String item : value.preparedStatementNames) {
            methodBuilder.beginControlFlow("if ($L!=null)", item);
            methodBuilder.addStatement("$L.close()", item);
            methodBuilder.addStatement("$L=null", item);
            methodBuilder.endControlFlow();
        }
        builder.addMethod(methodBuilder.build());
    }
    TypeSpec typeSpec = builder.build();
    JavaWriterHelper.writeJava2File(filer, packageName, typeSpec);
}
Also used : WildcardTypeName(com.squareup.javapoet.WildcardTypeName) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) TypeName(com.squareup.javapoet.TypeName) MethodSpec(com.squareup.javapoet.MethodSpec) Builder(com.squareup.javapoet.TypeSpec.Builder) BindTypeContext(com.abubusoft.kripton.processor.bind.BindTypeContext) FieldSpec(com.squareup.javapoet.FieldSpec) SQLiteEvent(com.abubusoft.kripton.android.sqlite.SQLiteEvent) BindDao(com.abubusoft.kripton.android.annotation.BindDao) Dao(com.abubusoft.kripton.android.sqlite.Dao) BindGeneratedDao(com.abubusoft.kripton.android.annotation.BindGeneratedDao) SQLiteModelMethod(com.abubusoft.kripton.processor.sqlite.model.SQLiteModelMethod) PublishSubject(io.reactivex.subjects.PublishSubject) WeakReference(java.lang.ref.WeakReference) Collection(java.util.Collection) KriptonComputableLiveData(com.abubusoft.kripton.android.sqlite.livedata.KriptonComputableLiveData) PackageElement(javax.lang.model.element.PackageElement) Collections(java.util.Collections) SQLContext(com.abubusoft.kripton.android.sqlite.SQLContext) HashSet(java.util.HashSet) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) TypeSpec(com.squareup.javapoet.TypeSpec)

Aggregations

PackageElement (javax.lang.model.element.PackageElement)133 TypeElement (javax.lang.model.element.TypeElement)92 Element (javax.lang.model.element.Element)51 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