Search in sources :

Example 16 with CodeBlock

use of com.squareup.javapoet.CodeBlock in project CoreData by FangCloud-Android.

the class EntityProcessor method createEntityDao.

public void createEntityDao(TypeElement element) throws IOException {
    EntityDetail entityDetail = EntityDetail.parse(processingEnv, element);
    // 实体类的class
    ClassName classEntity = ClassName.bestGuess(element.asType().toString());
    if (entityDetail.getPrimaryKey() == null) {
        throw new RuntimeException(classEntity.reflectionName() + " 没有主键");
    }
    List<Property> propertyList = entityDetail.getProperties(processingEnv);
    // 1、找出tableName,PrimaryKeyName ok
    // 2、找出所有的PropertyConverter,并生成局部变量,类似 __TagListConverter ok
    // 3、找出所有关联对象 @Relation,并生成对应的dao 类似 __AuthorCoreDao ok
    // 4、onCreate方法,初始化 关联对象对应的 dao ok
    // 5、getInsertSql, 返回插入的sql语句 ok
    // 6、getCreateTableSql,返回建表语句
    // 7、getTableProperties,返回所有的表结构
    // 8、绑定数据
    // dao的java名字
    String daoName = String.format("%sCoreDaoImpl", entityDetail.getEntityName());
    TypeSpec.Builder daoTypeBuilder = TypeSpec.classBuilder(daoName).addModifiers(Modifier.PUBLIC, Modifier.FINAL).superclass(ParameterizedTypeName.get(classCoreDao, classEntity));
    List<Element> convertElements = entityDetail.getConvertElements(processingEnv);
    // static 代码块
    CodeBlock convertStaticBlock = CreateConvertStatement.buildConvertStatic(convertElements);
    if (convertStaticBlock != null) {
        daoTypeBuilder.addStaticBlock(convertStaticBlock);
    }
    // 创建convert
    List<FieldSpec> convertFieldSpecs = CreateConvertStatement.bindComvertFields(convertElements);
    if (convertFieldSpecs != null) {
        for (FieldSpec fieldSpec : convertFieldSpecs) {
            daoTypeBuilder.addField(fieldSpec);
        }
    }
    // onCreate方法
    // 创建关联的dao
    List<Element> relationElements = entityDetail.getRelationElements();
    MethodSpec.Builder onCreateMethodBuilder = MethodSpec.methodBuilder("onCreate").addModifiers(Modifier.PROTECTED).returns(void.class).addParameter(classCoreData, "coreData").addStatement("super.onCreate($N)", "coreData");
    for (Element relationElement : relationElements) {
        TypeMirror typeMirror = relationElement.asType();
        ClassName classRelation = ClassName.bestGuess(typeMirror.toString());
        String daoFieldName = Utils.relationDaoName(classRelation);
        FieldSpec fieldSpec = FieldSpec.builder(ParameterizedTypeName.get(classCoreDao, classRelation), daoFieldName, Modifier.PRIVATE).build();
        daoTypeBuilder.addField(fieldSpec);
        onCreateMethodBuilder.addStatement("$N = coreData.dao($T.class)", daoFieldName, classRelation);
    }
    MethodSpec onCreateMethod = onCreateMethodBuilder.build();
    // getCreateTableSql 方法,用来获取建表语句
    MethodSpec getCreateTableSqlMethod = MethodSpec.methodBuilder("getCreateTableSql").addModifiers(Modifier.PROTECTED).returns(String.class).addStatement("return $S", SqlBuilder.buildCreateSql(entityDetail.getTableName(), propertyList, true)).build();
    // getInsertSql 方法,用来获取插入语句
    MethodSpec getInsertSqlMethod = MethodSpec.methodBuilder("getInsertSql").addModifiers(Modifier.PROTECTED).returns(String.class).addStatement("return $S", Utils.getInsertSql(entityDetail.getTableName(), propertyList)).build();
    // bindStatement 用来绑定数据
    MethodSpec bindStatementMethod = new BindStatementMethod(processingEnv, entityDetail).build();
    // replaceInternal 方法,用来处理关系型数据
    MethodSpec replaceInternalMethod = new ReplaceInternalMethod(processingEnv, entityDetail).build();
    // 创建 getTableName 方法,返回tableName
    MethodSpec getTableNameMethod = MethodSpec.methodBuilder("getTableName").addModifiers(Modifier.PUBLIC).returns(String.class).addStatement("return $S", entityDetail.getTableName()).build();
    // 创建 getPrimaryKeyName 方法,返回 主键的名字
    MethodSpec getPrimaryKeyNameMethod = MethodSpec.methodBuilder("getPrimaryKeyName").addModifiers(Modifier.PUBLIC).returns(String.class).addStatement("return $S", Utils.getColumnName(entityDetail.getPrimaryKey())).build();
    // 创建 bindCursor 方法,绑定游标数据到模型
    MethodSpec bindCursorMethod = new BindCursorMethod(processingEnv, entityDetail).build();
    // 创建 getTableProperties 方法,返回所有字段相关的 Property
    ParameterizedTypeName listPropertyType = ParameterizedTypeName.get(ClassName.get(ArrayList.class), classCoreProperty);
    MethodSpec.Builder getTablePropertiesBuilder = MethodSpec.methodBuilder("getTableProperties").addModifiers(Modifier.PUBLIC).returns(ParameterizedTypeName.get(ClassName.get(List.class), classCoreProperty));
    getTablePropertiesBuilder.addStatement("$T list = new $T()", listPropertyType, listPropertyType);
    for (Property property : propertyList) {
        getTablePropertiesBuilder.addStatement("list.add(new $T($S, $T.class, $N))", classCoreProperty, property.name, Utils.getTypeNameByType(property.type), String.valueOf(property.primaryKey));
    }
    getTablePropertiesBuilder.addStatement("return list");
    daoTypeBuilder.addMethod(onCreateMethod).addMethod(getTableNameMethod).addMethod(getPrimaryKeyNameMethod).addMethod(getTablePropertiesBuilder.build()).addMethod(getCreateTableSqlMethod).addMethod(getInsertSqlMethod).addMethod(bindStatementMethod).addMethod(replaceInternalMethod).addMethod(bindCursorMethod);
    JavaFile javaFile = JavaFile.builder(entityDetail.getEntityPackageName(processingEnv), daoTypeBuilder.build()).build();
    javaFile.writeTo(processingEnv.getFiler());
    System.out.println(element.getSimpleName());
    System.out.println(processingEnv.getElementUtils().getPackageOf(element).getQualifiedName());
}
Also used : MethodSpec(com.squareup.javapoet.MethodSpec) TypeElement(javax.lang.model.element.TypeElement) Element(javax.lang.model.element.Element) CodeBlock(com.squareup.javapoet.CodeBlock) ArrayList(java.util.ArrayList) BindCursorMethod(com.coredata.compiler.method.BindCursorMethod) FieldSpec(com.squareup.javapoet.FieldSpec) ReplaceInternalMethod(com.coredata.compiler.method.ReplaceInternalMethod) BindStatementMethod(com.coredata.compiler.method.BindStatementMethod) TypeMirror(javax.lang.model.type.TypeMirror) ClassName(com.squareup.javapoet.ClassName) JavaFile(com.squareup.javapoet.JavaFile) Property(com.coredata.db.Property) TypeSpec(com.squareup.javapoet.TypeSpec) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName)

Example 17 with CodeBlock

use of com.squareup.javapoet.CodeBlock in project CoreData by FangCloud-Android.

the class CreateConvertStatement method buildConvertStatic.

public static CodeBlock buildConvertStatic(List<Element> convertElements) {
    CodeBlock.Builder builder = CodeBlock.builder();
    if (convertElements == null) {
        return null;
    }
    for (Element convertElement : convertElements) {
        Convert convert = convertElement.getAnnotation(Convert.class);
        ClassName classConverter = ClassName.bestGuess(Utils.getConverterType(convert).toString());
        String packageName = classConverter.packageName();
        String name = classConverter.simpleName();
        System.out.println("BindConvertStatement----packageName:" + packageName);
        System.out.println("BindConvertStatement----name:" + name);
        if (SERIALIZABLE_CLASS_NAME.equals(classConverter) || SERIALIZABLE_LIST_CLASS_NAME.equals(classConverter)) {
            TypeName typeName1 = ClassName.get(convertElement.asType());
            System.out.println("BindConvertStatement----typeName:" + typeName1.toString());
            TypeName typeName = findSerializableType(typeName1);
            if (typeName != null) {
                builder.addStatement("$T.registerSerializableClass($T.class)", classCoreData, typeName);
            }
        }
    }
    return builder.build();
}
Also used : TypeName(com.squareup.javapoet.TypeName) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) Convert(com.coredata.annotation.Convert) Element(javax.lang.model.element.Element) CodeBlock(com.squareup.javapoet.CodeBlock) ClassName(com.squareup.javapoet.ClassName)

Example 18 with CodeBlock

use of com.squareup.javapoet.CodeBlock in project butterknife by JakeWharton.

the class FieldCollectionViewBinding method render.

CodeBlock render() {
    CodeBlock.Builder builder = CodeBlock.builder().add("target.$L = $T.$L(", name, UTILS, kind.factoryName);
    for (int i = 0; i < ids.size(); i++) {
        if (i > 0) {
            builder.add(", ");
        }
        builder.add("\n");
        boolean requiresCast = requiresCast(type);
        if (!requiresCast && !required) {
            builder.add("source.findViewById($L)", ids.get(i).code);
        } else {
            builder.add("$T.find", UTILS);
            builder.add(required ? "RequiredView" : "OptionalView");
            if (requiresCast) {
                builder.add("AsType");
            }
            builder.add("(source, $L, \"field '$L'\"", ids.get(i).code, name);
            if (requiresCast) {
                TypeName rawType = type;
                if (rawType instanceof ParameterizedTypeName) {
                    rawType = ((ParameterizedTypeName) rawType).rawType;
                }
                builder.add(", $T.class", rawType);
            }
            builder.add(")");
        }
    }
    return builder.add(")").build();
}
Also used : TypeName(com.squareup.javapoet.TypeName) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) CodeBlock(com.squareup.javapoet.CodeBlock) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName)

Example 19 with CodeBlock

use of com.squareup.javapoet.CodeBlock in project AndroidLife by CaMnter.

the class FieldCollectionViewBinding method render.

/**
 * 为 @BindViews 生成代码块
 *
 * @return CodeBlock
 */
CodeBlock render() {
    CodeBlock.Builder builder = CodeBlock.builder().add("target.$L = $T.$L(", name, UTILS, kind.factoryName);
    for (int i = 0; i < ids.size(); i++) {
        if (i > 0) {
            builder.add(", ");
        }
        builder.add("\n");
        boolean requiresCast = requiresCast(type);
        if (!requiresCast && !required) {
            builder.add("source.findViewById($L)", ids.get(i).code);
        } else {
            builder.add("$T.find", UTILS);
            builder.add(required ? "RequiredView" : "OptionalView");
            if (requiresCast) {
                builder.add("AsType");
            }
            builder.add("(source, $L, \"field '$L'\"", ids.get(i).code, name);
            if (requiresCast) {
                TypeName rawType = type;
                if (rawType instanceof ParameterizedTypeName) {
                    rawType = ((ParameterizedTypeName) rawType).rawType;
                }
                builder.add(", $T.class", rawType);
            }
            builder.add(")");
        }
    }
    return builder.add(")").build();
}
Also used : TypeName(com.squareup.javapoet.TypeName) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) CodeBlock(com.squareup.javapoet.CodeBlock) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName)

Example 20 with CodeBlock

use of com.squareup.javapoet.CodeBlock in project AndroidLife by CaMnter.

the class RouterClass method setFieldValueMethodBuilder.

/**
 * SmartRouter # setFieldValue(@NonNull final Activity activity)
 *
 * @return MethodSpec.Builder
 */
private MethodSpec.Builder setFieldValueMethodBuilder() {
    // public void setFieldValue(@NonNull Activity activity)
    final MethodSpec.Builder setFieldValueMethodBuilder = MethodSpec.methodBuilder("setFieldValue").addAnnotation(Override.class).addModifiers(Modifier.PUBLIC).returns(TypeName.VOID).addParameter(createNonNullParameter(this.annotatedElementTypeName, "activity", Modifier.FINAL));
    // final Intent intent = activity.getIntent()
    if (!this.routerFieldAnnotationList.isEmpty()) {
        setFieldValueMethodBuilder.addCode(CodeBlock.of("final $T intent = activity.getIntent();\n", ANDROID_INTENT));
        setFieldValueMethodBuilder.addCode(CodeBlock.of("final $T uri = intent.getData();\n", ANDROID_URI));
        setFieldValueMethodBuilder.addCode(CodeBlock.of("if (uri == null) return;\n\n"));
    }
    final List<CodeBlock> codeBlocks = new ArrayList<>();
    for (RouterFieldAnnotation routerFieldAnnotation : this.routerFieldAnnotationList) {
        final String fieldTypeString = routerFieldAnnotation.getFieldType().toString();
        final String fieldName = routerFieldAnnotation.getFieldName().toString();
        final String fieldValue = routerFieldAnnotation.getFieldValue();
        codeBlocks.clear();
        switch(fieldTypeString) {
            case CHAR:
            case BOXED_CHAR:
                final String uriParameterName = "uri" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
                codeBlocks.add(CodeBlock.of("final String $L = uri.getQueryParameter($S);\n", uriParameterName, fieldValue));
                codeBlocks.add(CodeBlock.of("if (!$T.isEmpty($L)) {\n", ANDROID_TEXT_UTILS, uriParameterName));
                codeBlocks.add(CodeBlock.of("    activity.$1L = $2L.charAt(0);\n", fieldName, uriParameterName));
                codeBlocks.add(CodeBlock.of("}\n"));
                break;
            case BYTE:
            case BOXED_BYTE:
                codeBlocks.addAll(this.getFieldValueCodeBlock(JAVA_BOXED_BYTE, fieldName, fieldValue));
                break;
            case SHORT:
            case BOXED_SHORT:
                codeBlocks.addAll(this.getFieldValueCodeBlock(JAVA_BOXED_SHORT, fieldName, fieldValue));
                break;
            case INT:
            case BOXED_INT:
                codeBlocks.addAll(this.getFieldValueCodeBlock(JAVA_BOXED_INT, fieldName, fieldValue));
                break;
            case FLOAT:
            case BOXED_FLOAT:
                codeBlocks.addAll(this.getFieldValueCodeBlock(JAVA_BOXED_FLOAT, fieldName, fieldValue));
                break;
            case DOUBLE:
            case BOXED_DOUBLE:
                codeBlocks.addAll(this.getFieldValueCodeBlock(JAVA_BOXED_DOUBLE, fieldName, fieldValue));
                break;
            case LONG:
            case BOXED_LONG:
                codeBlocks.addAll(this.getFieldValueCodeBlock(JAVA_BOXED_LONG, fieldName, fieldValue));
                break;
            case BOOLEAN:
            case BOXED_BOOLEAN:
                codeBlocks.addAll(this.getFieldValueCodeBlock(JAVA_BOXED_BOOLEAN, fieldName, fieldValue));
                break;
            case STRING:
                codeBlocks.add(CodeBlock.of("activity.$L = uri.getQueryParameter($S);\n", fieldName, fieldValue));
                break;
        }
        if (codeBlocks.isEmpty()) {
            continue;
        }
        for (CodeBlock block : codeBlocks) {
            setFieldValueMethodBuilder.addCode(block);
        }
    }
    return setFieldValueMethodBuilder;
}
Also used : MethodSpec(com.squareup.javapoet.MethodSpec) CodeBlock(com.squareup.javapoet.CodeBlock) ArrayList(java.util.ArrayList)

Aggregations

CodeBlock (com.squareup.javapoet.CodeBlock)42 MethodSpec (com.squareup.javapoet.MethodSpec)19 TypeMirror (javax.lang.model.type.TypeMirror)13 ParameterizedTypeName (com.squareup.javapoet.ParameterizedTypeName)11 TypeName (com.squareup.javapoet.TypeName)10 CompilationAbstractTest (com.google.auto.value.extension.serializable.serializer.utils.CompilationAbstractTest)8 ClassName (com.squareup.javapoet.ClassName)8 WireField (com.squareup.wire.WireField)8 Field (com.squareup.wire.schema.Field)8 ByteString (okio.ByteString)8 Test (org.junit.Test)8 JvmLanguages.builtInAdapterString (com.squareup.wire.schema.internal.JvmLanguages.builtInAdapterString)7 ArrayList (java.util.ArrayList)7 Serializer (com.google.auto.value.extension.serializable.serializer.interfaces.Serializer)6 ParameterSpec (com.squareup.javapoet.ParameterSpec)6 AnnotationSpec (com.squareup.javapoet.AnnotationSpec)4 TypeSpec (com.squareup.javapoet.TypeSpec)3 Element (javax.lang.model.element.Element)3 Predicate (com.google.common.base.Predicate)2 FieldSpec (com.squareup.javapoet.FieldSpec)2