Search in sources :

Example 16 with JavaFile

use of com.squareup.javapoet.JavaFile in project ucsFramework by cjsoftware-lib.

the class ProxyQueueBuilder method buildClass.

@Override
public ClassName buildClass(TypeElement proxiedInterface) {
    ClassName generatedProxyQueueExecutorClassName = ClassName.get(this.qualifiedPackageName, String.format(GENERATED_PROXY_QUEUE_EXECUTOR_CLASS_NAME_TEMPLATE, sanitiseClassName(proxiedInterface.getSimpleName().toString())));
    TypeSpec.Builder classBuilder = TypeSpec.classBuilder(generatedProxyQueueExecutorClassName).addModifiers(Modifier.PUBLIC).addSuperinterface(TypeName.get(proxiedInterface.asType())).addSuperinterface(Runnable.class);
    addStandardCode(classBuilder, proxiedInterface, strongReference, keepLastCallOnly);
    int methodId = 1;
    List<? extends Element> relevantElements = getRelevantMembers(proxiedInterface);
    for (Element interfaceElement : relevantElements) {
        if (interfaceElement.getKind() == ElementKind.METHOD) {
            ExecutableElement methodElement = (ExecutableElement) interfaceElement;
            if (!methodElement.getModifiers().contains(Modifier.FINAL)) {
                if (TypeKind.VOID == methodElement.getReturnType().getKind()) {
                    TypeSpec cacheClass = buildCacheClass(proxiedInterface, methodElement, methodId);
                    classBuilder.addType(cacheClass);
                    addImplementation(classBuilder, proxiedInterface, (ExecutableElement) interfaceElement, cacheClass);
                    methodId++;
                } else {
                    warningMessage("Methods with return types not allowed in ProxyQueueExecutor", interfaceElement);
                }
            }
        }
    }
    TypeSpec builtClass = classBuilder.build();
    try {
        JavaFile javaFile = JavaFile.builder(this.qualifiedPackageName, builtClass).addFileComment("Generated Code, do not modify.").build();
        javaFile.writeTo(getProcessorModel().getFiler());
    } catch (IOException e) {
        fatalErrorMessage("Exception writing java file: " + e.toString(), proxiedInterface);
    }
    return generatedProxyQueueExecutorClassName;
}
Also used : 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) ClassName(com.squareup.javapoet.ClassName) JavaFile(com.squareup.javapoet.JavaFile) IOException(java.io.IOException) TypeSpec(com.squareup.javapoet.TypeSpec)

Example 17 with JavaFile

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

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

the class ButterKnifeProcessor method process.

/**
 * 1.扫描 R class,并解析
 * 2.处理注解,生成对应 BindingSet.Builder Map 缓存
 * 3.处理 BindingSet.Builder Map 缓存,转化为 BindingSet Map 缓存
 * 4.从 BindingSet Map 缓存中拿到每一个 BindingSet,生成 JavaFile
 * 5.生成 class 文件
 *
 * @param elements elements
 * @param env RoundEnvironment
 * @return 是否退出
 */
@Override
public boolean process(Set<? extends TypeElement> elements, RoundEnvironment env) {
    Map<TypeElement, BindingSet> bindingMap = findAndParseTargets(env);
    for (Map.Entry<TypeElement, BindingSet> entry : bindingMap.entrySet()) {
        TypeElement typeElement = entry.getKey();
        BindingSet binding = entry.getValue();
        JavaFile javaFile = binding.brewJava(sdk);
        try {
            javaFile.writeTo(filer);
        } catch (IOException e) {
            error(typeElement, "Unable to write binding for type %s: %s", typeElement, e.getMessage());
        }
    }
    return false;
}
Also used : TypeElement(javax.lang.model.element.TypeElement) JavaFile(com.squareup.javapoet.JavaFile) IOException(java.io.IOException) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap)

Example 19 with JavaFile

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

the class FinalRClassBuilder method brewJava.

/**
 * JavaPoet 生成 R2
 *
 * @param rFile R.java File
 * @param outputDir R2.java 输出文件夹
 * @param packageName 包名
 * @param className R2 name
 * @throws Exception
 */
public static void brewJava(File rFile, File outputDir, String packageName, String className) throws Exception {
    /*
     * JavaParser 解析 R.java File
     * 获取到 TypeDeclaration
     */
    CompilationUnit compilationUnit = JavaParser.parse(rFile);
    TypeDeclaration resourceClass = compilationUnit.getTypes().get(0);
    /*
     * 定义 R2.java class
     */
    TypeSpec.Builder result = TypeSpec.classBuilder(className).addModifiers(PUBLIC).addModifiers(FINAL);
    /*
     * 遍历 R.java File 的每一个节点( 内部类或者接口 --> ClassOrInterfaceDeclaration )
     * 添加到 R2.java 内
     * 这里是给 TypeSpec 添加生成 内部类 的 语句
     */
    for (Node node : resourceClass.getChildNodes()) {
        if (node instanceof ClassOrInterfaceDeclaration) {
            addResourceType(Arrays.asList(SUPPORTED_TYPES), result, (ClassOrInterfaceDeclaration) node);
        }
    }
    JavaFile finalR = JavaFile.builder(packageName, result.build()).addFileComment("Generated code from Butter Knife gradle plugin. Do not modify!").build();
    finalR.writeTo(outputDir);
}
Also used : CompilationUnit(com.github.javaparser.ast.CompilationUnit) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) Node(com.github.javaparser.ast.Node) JavaFile(com.squareup.javapoet.JavaFile) TypeDeclaration(com.github.javaparser.ast.body.TypeDeclaration) TypeSpec(com.squareup.javapoet.TypeSpec)

Example 20 with JavaFile

use of com.squareup.javapoet.JavaFile in project kripton by xcesco.

the class JavaWriterHelper method writeJava2File.

/**
 * @param filer
 * @param packageName
 * @param typeSpec
 * @throws IOException
 */
public static void writeJava2File(Filer filer, String packageName, TypeSpec typeSpec) throws IOException {
    JavaFile target = JavaFile.builder(packageName, typeSpec).skipJavaLangImports(true).build();
    target.writeTo(filer);
}
Also used : 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