Search in sources :

Example 36 with JavaFile

use of com.squareup.javapoet.JavaFile in project T-MVP by north2016.

the class ApiFactoryProcessor method process.

@Override
public void process(RoundEnvironment roundEnv, AnnotationProcessor mAbstractProcessor) {
    String CLASS_NAME = "ApiFactory";
    String DATA_ARR_CLASS = "DataArr";
    TypeSpec.Builder tb = classBuilder(CLASS_NAME).addModifiers(PUBLIC, FINAL).addJavadoc("@ API工厂 此类由apt自动生成");
    try {
        for (TypeElement element : ElementFilter.typesIn(roundEnv.getElementsAnnotatedWith(ApiFactory.class))) {
            mAbstractProcessor.mMessager.printMessage(Diagnostic.Kind.NOTE, "正在处理: " + element.toString());
            for (Element e : element.getEnclosedElements()) {
                ExecutableElement executableElement = (ExecutableElement) e;
                MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(e.getSimpleName().toString()).addJavadoc("@此方法由apt自动生成").addModifiers(PUBLIC, STATIC);
                if (TypeName.get(executableElement.getReturnType()).toString().contains(DATA_ARR_CLASS)) {
                    // 返回列表数据
                    methodBuilder.returns(ClassName.get("io.reactivex", "Flowable"));
                    Map<String, Object> params = new HashMap<>();
                    methodBuilder.addParameter(params.getClass(), "param");
                    ClassName apiUtil = ClassName.get("com.base.util", "ApiUtil");
                    ClassName C = ClassName.get("com", "C");
                    CodeBlock.Builder blockBuilder = CodeBlock.builder();
                    int len = executableElement.getParameters().size();
                    for (int i = 0; i < len; i++) {
                        VariableElement ep = executableElement.getParameters().get(i);
                        boolean isLast = i == len - 1;
                        String split = (isLast ? "" : ",");
                        switch(ep.getSimpleName().toString()) {
                            case "include":
                                blockBuilder.add("$L.getInclude(param)" + split, apiUtil);
                                break;
                            case "where":
                                blockBuilder.add("$L.getWhere(param)" + split, apiUtil);
                                break;
                            case "skip":
                                blockBuilder.add("$L.getSkip(param)" + split, apiUtil);
                                break;
                            case "limit":
                                blockBuilder.add("$L.PAGE_COUNT" + split, C);
                                break;
                            case "order":
                                blockBuilder.add("$L._CREATED_AT" + split, C);
                                break;
                        }
                    }
                    methodBuilder.addStatement("return $T.getInstance()" + ".service.$L($L)" + ".compose($T.io_main())", ClassName.get("com.api", "Api"), e.getSimpleName().toString(), blockBuilder.build().toString(), ClassName.get("com.base.util.helper", "RxSchedulers"));
                    tb.addMethod(methodBuilder.build());
                } else {
                    // 返回普通数据
                    methodBuilder.returns(TypeName.get(executableElement.getReturnType()));
                    String paramsString = "";
                    for (VariableElement ep : executableElement.getParameters()) {
                        methodBuilder.addParameter(TypeName.get(ep.asType()), ep.getSimpleName().toString());
                        paramsString += ep.getSimpleName().toString() + ",";
                    }
                    methodBuilder.addStatement("return $T.getInstance()" + ".service.$L($L)" + ".compose($T.io_main())", ClassName.get("com.api", "Api"), e.getSimpleName().toString(), paramsString.substring(0, paramsString.length() - 1), ClassName.get("com.base.util.helper", "RxSchedulers"));
                    tb.addMethod(methodBuilder.build());
                }
            }
        }
        // 生成源代码
        JavaFile javaFile = JavaFile.builder(Utils.PackageName, tb.build()).build();
        // 在 app module/build/generated/source/apt 生成一份源代码
        javaFile.writeTo(mAbstractProcessor.mFiler);
    } catch (FilerException e) {
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : ApiFactory(com.app.annotation.apt.ApiFactory) MethodSpec(com.squareup.javapoet.MethodSpec) HashMap(java.util.HashMap) TypeElement(javax.lang.model.element.TypeElement) VariableElement(javax.lang.model.element.VariableElement) TypeElement(javax.lang.model.element.TypeElement) ExecutableElement(javax.lang.model.element.ExecutableElement) Element(javax.lang.model.element.Element) ExecutableElement(javax.lang.model.element.ExecutableElement) CodeBlock(com.squareup.javapoet.CodeBlock) VariableElement(javax.lang.model.element.VariableElement) IOException(java.io.IOException) IOException(java.io.IOException) FilerException(javax.annotation.processing.FilerException) ClassName(com.squareup.javapoet.ClassName) JavaFile(com.squareup.javapoet.JavaFile) FilerException(javax.annotation.processing.FilerException) TypeSpec(com.squareup.javapoet.TypeSpec)

Example 37 with JavaFile

use of com.squareup.javapoet.JavaFile in project T-MVP by north2016.

the class RouterProcessor method process.

@Override
public void process(RoundEnvironment roundEnv, AnnotationProcessor mAbstractProcessor) {
    String CLASS_NAME = "TRouter";
    TypeSpec.Builder tb = classBuilder(CLASS_NAME).addModifiers(PUBLIC, FINAL).addJavadoc("@ 全局路由器 此类由apt自动生成");
    FieldSpec extraField = FieldSpec.builder(ParameterizedTypeName.get(HashMap.class, String.class, Object.class), "mCurActivityExtra").addModifiers(Modifier.PUBLIC, Modifier.STATIC).build();
    tb.addField(extraField);
    MethodSpec.Builder methodBuilder1 = MethodSpec.methodBuilder("go").addJavadoc("@此方法由apt自动生成").addModifiers(PUBLIC, STATIC).addParameter(String.class, "name").addParameter(HashMap.class, "extra").addParameter(ClassName.get("android.view", "View"), "view");
    MethodSpec.Builder methodBuilder2 = MethodSpec.methodBuilder("bind").addJavadoc("@此方法由apt自动生成").addModifiers(PUBLIC, STATIC).addParameter(ClassName.get("android.app", "Activity"), "mContext");
    List<ClassName> mList = new ArrayList<>();
    CodeBlock.Builder blockBuilderGo = CodeBlock.builder();
    CodeBlock.Builder blockBuilderBind = CodeBlock.builder();
    ClassName appClassName = ClassName.get("com", "App");
    blockBuilderGo.addStatement("mCurActivityExtra=extra");
    blockBuilderGo.addStatement("Activity mContext=$T.getAppContext().getCurActivity()", appClassName);
    // 括号开始
    blockBuilderGo.beginControlFlow(" switch (name)");
    blockBuilderBind.addStatement("if(mCurActivityExtra==null) return");
    // 括号开始
    blockBuilderBind.beginControlFlow(" switch (mContext.getClass().getSimpleName())");
    List<RouterActivityModel> mRouterActivityModels = new ArrayList<>();
    try {
        for (TypeElement element : ElementFilter.typesIn(roundEnv.getElementsAnnotatedWith(Router.class))) {
            ClassName currentType = ClassName.get(element);
            if (mList.contains(currentType))
                continue;
            mList.add(currentType);
            RouterActivityModel mRouterActivityModel = new RouterActivityModel();
            mRouterActivityModel.setElement(element);
            mRouterActivityModel.setActionName(element.getAnnotation(Router.class).value());
            List<Element> mExtraElements = new ArrayList<>();
            List<String> mExtraElementKeys = new ArrayList<>();
            for (Element childElement : element.getEnclosedElements()) {
                SceneTransition mSceneTransitionAnnotation = childElement.getAnnotation(SceneTransition.class);
                if (mSceneTransitionAnnotation != null) {
                    mRouterActivityModel.setSceneTransitionElementName(mSceneTransitionAnnotation.value());
                    mRouterActivityModel.setSceneTransitionElement(childElement);
                }
                Extra mExtraAnnotation = childElement.getAnnotation(Extra.class);
                if (mExtraAnnotation != null) {
                    mExtraElementKeys.add(mExtraAnnotation.value());
                    mExtraElements.add(childElement);
                }
            }
            mRouterActivityModel.setExtraElementKeys(mExtraElementKeys);
            mRouterActivityModel.setExtraElements(mExtraElements);
            boolean isNeedBind = (mExtraElementKeys != null && mExtraElementKeys.size() > 0 || mRouterActivityModel.getSceneTransitionElement() != null);
            mRouterActivityModel.setNeedBind(isNeedBind);
            mRouterActivityModels.add(mRouterActivityModel);
        }
        ClassName mActivityCompatName = ClassName.get("android.support.v4.app", "ActivityCompat");
        ClassName mIntentClassName = ClassName.get("android.content", "Intent");
        ClassName mActivityOptionsCompatName = ClassName.get("android.support.v4.app", "ActivityOptionsCompat");
        for (RouterActivityModel item : mRouterActivityModels) {
            // 1
            blockBuilderGo.add("case $S: \n", item.getActionName());
            if (item.isNeedBind())
                // 1
                blockBuilderBind.add("case $S: \n", item.getElement().getSimpleName());
            if (item.getExtraElements() != null && item.getExtraElements().size() > 0) {
                for (int i = 0; i < item.getExtraElements().size(); i++) {
                    Element mFiled = item.getExtraElements().get(i);
                    blockBuilderBind.add(// 1
                    "(($T)mContext)." + // 2
                    "$L" + // 3
                    "= ($T) " + // 4
                    "mCurActivityExtra.get(" + // 5
                    "$S);\n", // 1
                    item.getElement(), // 2
                    mFiled, // 3
                    mFiled, // 5
                    item.getExtraElementKeys().get(i));
                // 5
                }
            }
            if (item.getSceneTransitionElement() != null) {
                blockBuilderGo.add(// 2
                "$L.startActivity(mContext," + // 3
                "\nnew $L(mContext," + // 4
                "\n$L.class)," + // 5
                "\n$T.makeSceneTransitionAnimation(" + // 6
                "\nmContext,view," + // 7
                "\n$S).toBundle());", // 2
                mActivityCompatName, // 3
                mIntentClassName, // 4
                item.getElement(), // 5
                mActivityOptionsCompatName, // 6
                item.getSceneTransitionElementName());
                blockBuilderBind.add(// 2
                "$T.setTransitionName(" + // 3
                "(($T)mContext).mViewBinding." + // 4
                "$L, " + // 5
                "$S);\n", // 2
                ClassName.get("android.support.v4.view", "ViewCompat"), // 3
                item.getElement(), // 4
                item.getSceneTransitionElement(), // 5
                item.getSceneTransitionElementName());
            } else {
                blockBuilderGo.add(// 2
                "mContext.startActivity(" + // 3
                "\nnew $L(mContext," + // 7
                "\n$L.class));", // 3
                mIntentClassName, // 4
                item.getElement());
            }
            // 1
            blockBuilderGo.addStatement("\nbreak");
            // 1
            if (item.isNeedBind())
                blockBuilderBind.addStatement("break");
        }
        blockBuilderGo.addStatement("default: break");
        blockBuilderGo.endControlFlow();
        methodBuilder1.addCode(blockBuilderGo.build());
        blockBuilderBind.addStatement("default: break");
        blockBuilderBind.endControlFlow();
        methodBuilder2.addCode(blockBuilderBind.build());
        tb.addMethod(methodBuilder1.build());
        tb.addMethod(methodBuilder2.build());
        // 增加go(action)和go(action,extra):两个重载方法
        tb.addMethod(MethodSpec.methodBuilder("go").addJavadoc("@此方法由apt自动生成").addModifiers(PUBLIC, STATIC).addParameter(String.class, "name").addParameter(HashMap.class, "extra").addCode("go(name,extra,null);\n").build());
        tb.addMethod(MethodSpec.methodBuilder("go").addJavadoc("@此方法由apt自动生成").addModifiers(PUBLIC, STATIC).addParameter(String.class, "name").addCode("go(name,null,null);\n").build());
        // 生成源代码
        JavaFile javaFile = JavaFile.builder(Utils.PackageName, tb.build()).build();
        // 在 app module/build/generated/source/apt 生成一份源代码
        javaFile.writeTo(mAbstractProcessor.mFiler);
    } catch (FilerException e) {
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : HashMap(java.util.HashMap) TypeElement(javax.lang.model.element.TypeElement) Element(javax.lang.model.element.Element) ArrayList(java.util.ArrayList) SceneTransition(com.app.annotation.apt.SceneTransition) ClassName(com.squareup.javapoet.ClassName) FilerException(javax.annotation.processing.FilerException) MethodSpec(com.squareup.javapoet.MethodSpec) TypeElement(javax.lang.model.element.TypeElement) CodeBlock(com.squareup.javapoet.CodeBlock) Router(com.app.annotation.apt.Router) IOException(java.io.IOException) FieldSpec(com.squareup.javapoet.FieldSpec) IOException(java.io.IOException) FilerException(javax.annotation.processing.FilerException) RouterActivityModel(com.app.apt.helper.RouterActivityModel) Extra(com.app.annotation.apt.Extra) JavaFile(com.squareup.javapoet.JavaFile) TypeSpec(com.squareup.javapoet.TypeSpec)

Example 38 with JavaFile

use of com.squareup.javapoet.JavaFile 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 39 with JavaFile

use of com.squareup.javapoet.JavaFile in project web3sdk by FISCO-BCOS.

the class Generator method write.

void write(String packageName, TypeSpec typeSpec, String destinationDir) throws IOException {
    JavaFile javaFile = JavaFile.builder(packageName, typeSpec).indent("    ").skipJavaLangImports(true).build();
    javaFile.writeTo(new File(destinationDir));
}
Also used : JavaFile(com.squareup.javapoet.JavaFile) JavaFile(com.squareup.javapoet.JavaFile) File(java.io.File)

Example 40 with JavaFile

use of com.squareup.javapoet.JavaFile in project coprhd-controller by CoprHD.

the class PrimitiveDoclet method start.

public static boolean start(RootDoc root) {
    KnownPaths.init(contentDirectory, outputDirectory);
    final List<ApiService> services = ApiDoclet.findApiServices(root.classes());
    final Path readMe = new File(outputDirectory + README).toPath();
    final Iterable<JavaFile> files = ApiPrimitiveMaker.makePrimitives(services);
    ImmutableList.Builder<String> lines = ImmutableList.<String>builder();
    lines.add(ReadMePreamble);
    for (final JavaFile file : files) {
        try {
            lines.add("<value>" + file.packageName + "." + file.typeSpec.name + "</value>");
            file.writeTo(new File(outputDirectory + SOURCE_DIR));
        } catch (IOException e) {
            throw new RuntimeException("Failed to write to output folder", e);
        }
    }
    try {
        Files.createDirectories(readMe.getParent());
        Files.write(readMe, lines.build(), Charset.forName("UTF-8"));
    } catch (IOException e) {
        throw new RuntimeException("Failed to write README", e);
    }
    return true;
}
Also used : Path(java.nio.file.Path) ApiService(com.emc.apidocs.model.ApiService) ImmutableList(com.google.common.collect.ImmutableList) JavaFile(com.squareup.javapoet.JavaFile) IOException(java.io.IOException) File(java.io.File) JavaFile(com.squareup.javapoet.JavaFile)

Aggregations

JavaFile (com.squareup.javapoet.JavaFile)68 TypeSpec (com.squareup.javapoet.TypeSpec)43 IOException (java.io.IOException)42 TypeElement (javax.lang.model.element.TypeElement)25 MethodSpec (com.squareup.javapoet.MethodSpec)21 ClassName (com.squareup.javapoet.ClassName)19 Element (javax.lang.model.element.Element)15 ExecutableElement (javax.lang.model.element.ExecutableElement)12 HashMap (java.util.HashMap)10 File (java.io.File)9 HashSet (java.util.HashSet)9 Map (java.util.Map)9 VariableElement (javax.lang.model.element.VariableElement)9 Builder (com.squareup.javapoet.TypeSpec.Builder)8 ArrayList (java.util.ArrayList)8 ProcessorException (com.github.mvp4g.mvp4g2.processor.ProcessorException)6 PackageElement (javax.lang.model.element.PackageElement)6 DeclaredType (javax.lang.model.type.DeclaredType)6 TypeMirror (javax.lang.model.type.TypeMirror)6 CodeBlock (com.squareup.javapoet.CodeBlock)5