Search in sources :

Example 56 with JavaFile

use of com.squareup.javapoet.JavaFile in project mvp4g2 by mvp4g.

the class PresenterGenerator method generate.

public void generate(PresenterMetaModel metaModel) throws ProcessorException {
    ClassName presenterrMetaDataClassName = ClassName.get(PresenterMetaData.class);
    ClassName presenterMetaDataKindClassName = ClassName.get(HandlerMetaData.Kind.class);
    ClassName presenterViewCreationMethodClassName = ClassName.get(Presenter.VIEW_CREATION_METHOD.class);
    for (String presenter : metaModel.getPresenterKeys()) {
        // check if element is existing (to avoid generating code for deleted items)
        if (this.processorUtils.doesExist(new ClassNameModel(presenter))) {
            PresenterMetaModel.PresenterData data = metaModel.getPresenterData(presenter);
            String className = this.processorUtils.createFullClassName(data.getPresenter().getPackage(), data.getPresenter().getSimpleName() + ProcessorConstants.META_DATA);
            TypeSpec.Builder typeSpec = TypeSpec.classBuilder(this.processorUtils.setFirstCharacterToUpperCase(className)).superclass(ParameterizedTypeName.get(presenterrMetaDataClassName, data.getPresenter().getTypeName(), data.getViewInterface().getTypeName())).addModifiers(Modifier.PUBLIC, Modifier.FINAL);
            // constructor ...
            MethodSpec.Builder constructor = MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC).addStatement("super($S, $T.PRESENTER, $N, $T.$L)", data.getPresenter().getClassName(), presenterMetaDataKindClassName, data.getIsMultiple(), presenterViewCreationMethodClassName, data.getViewCreationMethod());
            if (!metaModel.getPresenterData(presenter).isMultiple()) {
                constructor.addStatement("super.presenter = new $T()", data.getPresenter().getTypeName());
                if (Presenter.VIEW_CREATION_METHOD.FRAMEWORK.toString().equals(data.getViewCreationMethod())) {
                    constructor.addStatement("super.view = ($T) new $T()", data.getViewInterface().getTypeName(), data.getViewClass().getTypeName());
                } else {
                    constructor.addStatement("super.view = presenter.createView()");
                }
            }
            typeSpec.addMethod(constructor.build());
            JavaFile javaFile = JavaFile.builder(data.getPresenter().getPackage(), typeSpec.build()).build();
            try {
                javaFile.writeTo(this.processingEnvironment.getFiler());
            } catch (IOException e) {
                throw new ProcessorException("Unable to write generated file: >>" + data.getPresenter().getSimpleName() + ProcessorConstants.META_DATA + "<< -> exception: " + e.getMessage());
            }
        }
    }
}
Also used : HandlerMetaData(com.github.mvp4g.mvp4g2.core.internal.ui.HandlerMetaData) ProcessorException(com.github.mvp4g.mvp4g2.processor.ProcessorException) MethodSpec(com.squareup.javapoet.MethodSpec) IOException(java.io.IOException) Presenter(com.github.mvp4g.mvp4g2.core.ui.annotation.Presenter) PresenterMetaModel(com.github.mvp4g.mvp4g2.processor.model.PresenterMetaModel) ClassName(com.squareup.javapoet.ClassName) JavaFile(com.squareup.javapoet.JavaFile) ClassNameModel(com.github.mvp4g.mvp4g2.processor.model.intern.ClassNameModel) TypeSpec(com.squareup.javapoet.TypeSpec)

Example 57 with JavaFile

use of com.squareup.javapoet.JavaFile in project tiger by google.

the class GeneralInjectorGenerator method generate.

public void generate() {
    injectorBuilder = createInjectorBuilder();
    initializeBuilder = MethodSpec.methodBuilder(INITIALIZE_METHOD_NAME).addModifiers(Modifier.PUBLIC);
    // messager.printMessage(Kind.NOTE,
    // "generatedBindings: " + generatedBindings);
    // logger.n("" + keyToPackagedInjectorMap);
    generateCtor();
    preGenerateProduced();
    generateProduced();
    postGenerateProduced();
    // injectorBuilder.addMethod(initializeBuilder.build());
    // Write
    JavaFile javaFile = JavaFile.builder(getPackageString(), injectorBuilder.build()).build();
    try {
        // logger.n(
        // " package:%s\n%s",
        // getPackageString(),
        // new StringBuilder().append(javaFile.toJavaFileObject().getCharContent(true)).toString());
        javaFile.writeTo(processingEnv.getFiler());
    } catch (IOException e) {
        logger.e(e.toString());
    }
}
Also used : JavaFile(com.squareup.javapoet.JavaFile) IOException(java.io.IOException)

Example 58 with JavaFile

use of com.squareup.javapoet.JavaFile in project tiger by google.

the class Tiger2Processor method generateWrapperComponents.

/**
 * Generates Dagger component implementations that wrap around the core injectors.
 */
private void generateWrapperComponents(Set<TypeElement> components) {
    componentToBuilderMap = collectComponentToBuilderMap();
    for (TypeElement component : components) {
        CoreInjectorInfo coreInjector = componentToCoreInjectorMap.get(component);
        // Ignore orphan eitherComponents whose core injector is not generated.
        if (scopeSizer.getScopeSize(coreInjector) == -1) {
            continue;
        }
        ClassName coreInjectorClassName = getCoreInejectorClassName(coreInjectorPackage, coreInjector);
        String packageString = utils.getPackageString(component);
        String generatedComponentSimpleName = utils.getComponentImplementationSimpleNameFromInterface(component);
        messager.printMessage(Kind.NOTE, TAG + ".generateWrapperComponents: generated component " + generatedComponentSimpleName);
        TypeSpec.Builder componentBuilder = TypeSpec.classBuilder(generatedComponentSimpleName).addModifiers(Modifier.PUBLIC).addSuperinterface(TypeName.get(component.asType())).superclass(coreInjectorClassName);
        // Ctor with parent component, component dependencies and modules as parameters.
        MethodSpec.Builder ctorBuilder = MethodSpec.constructorBuilder().addModifiers(Modifier.PRIVATE);
        // Ctor parent component
        TypeElement parentComponent = componentToParentMap.get(component);
        StringBuilder callSuperStringBuilder = new StringBuilder("super(");
        boolean needLeadingComma = false;
        if (parentComponent != null) {
            needLeadingComma = true;
            ctorBuilder.addParameter(TypeName.get(parentComponent.asType()), utils.getSourceCodeName(parentComponent));
            // Cast the interface to implement which is a subclass of core injector therefore will be
            // accept by compiler.
            callSuperStringBuilder.append("($T) ").append(utils.getSourceCodeName(parentComponent));
        }
        // Ctor component dependencies parameters
        if (!coreInjectorToComponentDependencyMap.get(coreInjector).isEmpty()) {
            if (needLeadingComma) {
                callSuperStringBuilder.append(", ");
            }
            needLeadingComma = true;
            Set<TypeElement> deps = componentToComponentDependencyMap.get(component);
            for (TypeElement typeElement : utils.sortByFullName(coreInjectorToComponentDependencyMap.get(coreInjector))) {
                if (deps.contains(typeElement)) {
                    ctorBuilder.addParameter(TypeName.get(typeElement.asType()), utils.getSourceCodeName(typeElement));
                    callSuperStringBuilder.append(utils.getSourceCodeName(typeElement));
                } else {
                    callSuperStringBuilder.append("null");
                }
                callSuperStringBuilder.append(", ");
            }
            callSuperStringBuilder.delete(callSuperStringBuilder.length() - 2, callSuperStringBuilder.length());
        }
        // Ctor @BindsInstance parameters
        if (!coreInjectorToBindsInstanceMap.get(coreInjector).isEmpty()) {
            if (needLeadingComma) {
                callSuperStringBuilder.append(", ");
            }
            needLeadingComma = true;
            Set<BindingKey> bindsInstances = componentToBindsInstanceMap.get(component);
            for (BindingKey key : utils.sortBindingKeys(coreInjectorToBindsInstanceMap.get(coreInjector))) {
                if (bindsInstances.contains(key)) {
                    String sourceCodeName = utils.getSourceCodeNameHandlingBox(key, dependencies);
                    ctorBuilder.addParameter(key.getTypeName(), sourceCodeName);
                    callSuperStringBuilder.append(sourceCodeName);
                } else {
                    callSuperStringBuilder.append("null");
                }
                callSuperStringBuilder.append(", ");
            }
            callSuperStringBuilder.delete(callSuperStringBuilder.length() - 2, callSuperStringBuilder.length());
        }
        // Ctor module parameters
        Set<TypeElement> allComponentModules = getAllModulesOfComponentRecursively(component);
        List<TypeElement> sortedComponentPassedModules = utils.sortByFullName(utils.getNonNullaryCtorOnes(allComponentModules));
        Set<TypeElement> coreInjectorPassedModules = new HashSet<>();
        coreInjectorPassedModules.addAll(scopedPassedModules.get(coreInjector));
        coreInjectorPassedModules.addAll(unscopedPassedModules);
        List<TypeElement> sortedCoreInjectorPassedModules = utils.sortByFullName(coreInjectorPassedModules);
        if (!sortedCoreInjectorPassedModules.isEmpty()) {
            if (needLeadingComma) {
                callSuperStringBuilder.append(", ");
            }
            needLeadingComma = true;
            for (TypeElement typeElement : sortedCoreInjectorPassedModules) {
                if (sortedComponentPassedModules.contains(typeElement)) {
                    ctorBuilder.addParameter(TypeName.get(typeElement.asType()), utils.getSourceCodeName(typeElement));
                    callSuperStringBuilder.append(utils.getSourceCodeName(typeElement));
                } else {
                    callSuperStringBuilder.append("null");
                }
                callSuperStringBuilder.append(", ");
            }
            callSuperStringBuilder.delete(callSuperStringBuilder.length() - 2, callSuperStringBuilder.length());
        }
        callSuperStringBuilder.append(");");
        if (parentComponent != null) {
            CoreInjectorInfo coreInjectorInfo = componentToCoreInjectorMap.get(parentComponent);
            ctorBuilder.addCode(callSuperStringBuilder.toString(), // TODO: hack, restore
            getCoreInejectorClassName(coreInjectorPackage, coreInjectorInfo));
        // ClassName.get(
        // utils.getPackageString(parentComponent),
        // utils.getComponentImplementationSimpleNameFromInterface(parentComponent)));
        } else {
            ctorBuilder.addCode(callSuperStringBuilder.toString());
        }
        componentBuilder.addMethod(ctorBuilder.build());
        // Generate provision method
        // Generate Builder.
        @Nullable TypeElement expliciteBuilder = componentToBuilderMap.get(component);
        generateWrapperComponentBuilder(component, parentComponent, sortedComponentPassedModules, componentBuilder, coreInjector, expliciteBuilder);
        // Generate builder().
        ClassName builderClassName = ClassName.get(packageString, generatedComponentSimpleName, expliciteBuilder != null ? expliciteBuilder.getSimpleName().toString() : "Builder");
        MethodSpec.Builder builderMethodSpecBuilder = MethodSpec.methodBuilder("builder").addModifiers(Modifier.PUBLIC, Modifier.STATIC).returns(builderClassName);
        boolean isSubcomponent = utils.isSubcomponent(component);
        if (isSubcomponent) {
            builderMethodSpecBuilder.addParameter(ClassName.get(componentToParentMap.get(component).asType()), "v");
        }
        builderMethodSpecBuilder.addCode("return new $T($L);", builderClassName, isSubcomponent ? "v" : "");
        componentBuilder.addMethod(builderMethodSpecBuilder.build());
        JavaFile javaFile = JavaFile.builder(packageString, componentBuilder.build()).build();
        try {
            messager.printMessage(Kind.NOTE, String.format("%s: writing java file: %s", TAG, javaFile.toJavaFileObject().getName()));
            javaFile.writeTo(processingEnv.getFiler());
        } catch (IOException e) {
        // messager.printMessage(Kind.ERROR, e.toString());
        }
    }
}
Also used : MethodSpec(com.squareup.javapoet.MethodSpec) TypeElement(javax.lang.model.element.TypeElement) IOException(java.io.IOException) ClassName(com.squareup.javapoet.ClassName) JavaFile(com.squareup.javapoet.JavaFile) Nullable(javax.annotation.Nullable) TypeSpec(com.squareup.javapoet.TypeSpec) HashSet(java.util.HashSet)

Example 59 with JavaFile

use of com.squareup.javapoet.JavaFile in project tiger by google.

the class PackagedHubInterfaceGenerator method generate.

public void generate(String p) {
    logger.n("package: %s", p);
    provisionMethodGenerated.clear();
    interfaceBuilder = TypeSpec.interfaceBuilder(HUB_INTERFACE).addAnnotation(AnnotationSpec.builder(Generated.class).addMember("value", "$S", "dagger." + TAG).build()).addModifiers(Modifier.PUBLIC);
    packageElement = elements.getPackageElement(p);
    modules = new HashSet<>();
    ctorInjectedClasses = new HashSet<>();
    injectedClasses = new HashSet<>();
    packageString = p;
    collectModulesAndInjected();
    generateInterfaceForHub();
    JavaFile javaFile = JavaFile.builder(p, interfaceBuilder.build()).build();
    try {
        // logger.n(
        // "package:%s\n%s",
        // p,
        // new StringBuilder().append(javaFile.toJavaFileObject().getCharContent(true)).toString());
        javaFile.writeTo(processingEnv.getFiler());
    } catch (IOException e) {
        messager.printMessage(Kind.ERROR, "Failed to write " + javaFile + "\n" + e);
    }
}
Also used : Generated(javax.annotation.Generated) JavaFile(com.squareup.javapoet.JavaFile) IOException(java.io.IOException)

Example 60 with JavaFile

use of com.squareup.javapoet.JavaFile in project tiger by google.

the class ProxyGenerator method generateForPackage.

private void generateForPackage(PackageElement p) {
    Set<TypeElement> modules = new HashSet<>();
    Set<TypeElement> classesWithInject = new HashSet<>();
    // messager.printMessage(
    // Kind.NOTE,
    // TAG
    // + ".generateForPackage: "
    // + p
    // + "\nmodules: \n"
    // + modules
    // + " cls: "
    // + classesWithInject);
    collectModulesAndInjected(p, modules, classesWithInject);
    TypeSpec.Builder typeBuilder = TypeSpec.classBuilder(ClassName.get(p.getQualifiedName().toString(), TIGER_PROXY_NAME)).addAnnotation(AnnotationSpec.builder(Generated.class).addMember("value", "$S", GENERATOR_NAME).build()).addModifiers(Modifier.PUBLIC);
    for (TypeElement m : modules) {
        addMethodsCallingModuleMethods(typeBuilder, m);
    }
    for (TypeElement c : classesWithInject) {
        // }
        if (!utils.isGenericNotSpecialized(c.asType())) {
            addMethodCallingCtor(typeBuilder, c);
        }
        if (utils.hasInjectedFieldsOrMethodsRecursively(c, env)) {
            addInjectionMethod(typeBuilder, c);
        }
    // addMethodSettingFields(typeBuilder, c);
    // addMethodsCallingClassMethods(typeBuilder, c);
    }
    JavaFile javaFile = JavaFile.builder(p.getQualifiedName().toString(), typeBuilder.build()).build();
    try {
        messager.printMessage(Kind.NOTE, TAG + " write to file: " + javaFile.toJavaFileObject().getName() + "\n" + javaFile.toString() + "\n");
        javaFile.writeTo(env.getFiler());
    } catch (IOException e) {
        messager.printMessage(Kind.ERROR, e.toString());
    }
}
Also used : TypeElement(javax.lang.model.element.TypeElement) Builder(com.squareup.javapoet.TypeSpec.Builder) JavaFile(com.squareup.javapoet.JavaFile) IOException(java.io.IOException) HashSet(java.util.HashSet) TypeSpec(com.squareup.javapoet.TypeSpec)

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