Search in sources :

Example 26 with JavaFile

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

the class HubInjectorGenerator method generateGenericInjectorIfNeeded.

private void generateGenericInjectorIfNeeded(DependencyInfo dependencyInfo) {
    BindingKey dependant = dependencyInfo.getDependant();
    if (!generatedGenericInjectors.add(utils.getGenericInjectorName(dependant))) {
        return;
    }
    TypeSpec.Builder genericInjectorBuilder = TypeSpec.classBuilder(utils.getGenericInjectorSimpleName(dependant)).addAnnotation(AnnotationSpec.builder(Generated.class).addMember("value", "$S", GENERATOR_NAME).build()).addModifiers(Modifier.PUBLIC);
    TypeName returnType = dependant.getTypeName();
    MethodSpec.Builder generateBuilder = MethodSpec.methodBuilder("generate").addModifiers(Modifier.PUBLIC).returns(returnType);
    for (BindingKey key : utils.sortBindingKeys(dependencyInfo.getDependencies())) {
        generateBuilder.addParameter(key.getTypeName(), utils.getSourceCodeName(key));
    }
    DeclaredType type = (DeclaredType) utils.getTypeFromTypeName(returnType);
    TypeElement classElement = (TypeElement) type.asElement();
    ExecutableElement ctor = Preconditions.checkNotNull(utils.findInjectedCtor(classElement), "injector ctor not found for dI: " + dependencyInfo);
    TypeMirror ctorTypeMirror = types.asMemberOf(type, ctor);
    List<BindingKey> ctorDependencies = utils.getCtorDependencies(dependencies, dependant);
    StringBuilder statementBuilder = new StringBuilder("$T result = new $T(");
    for (BindingKey key : ctorDependencies) {
        statementBuilder.append(utils.getSourceCodeName(key)).append(", ");
    }
    utils.trimTrailing(statementBuilder, ", ");
    statementBuilder.append(")");
    generateBuilder.addStatement(statementBuilder.toString(), returnType, returnType);
    for (Element element : classElement.getEnclosedElements()) {
        if (element.getKind().equals(ElementKind.FIELD) && utils.isInjected(element)) {
            generateBuilder.addStatement("result.$N = $L", element.getSimpleName(), utils.getSourceCodeName(utils.getKeyForField(type, element)));
        }
        if (element.getKind().equals(ElementKind.METHOD) && utils.isInjected(element)) {
            statementBuilder = new StringBuilder("result.$L(");
            for (BindingKey key : utils.getDependenciesFromMethod((ExecutableType) types.asMemberOf(type, element), (ExecutableElement) element)) {
                statementBuilder.append(utils.getSourceCodeName(key)).append(", ");
            }
            utils.trimTrailing(statementBuilder, ", ");
            statementBuilder.append(")");
            generateBuilder.addStatement(statementBuilder.toString(), element.getSimpleName());
        }
    }
    generateBuilder.addStatement("return result");
    genericInjectorBuilder.addMethod(generateBuilder.build());
    JavaFile javaFile = JavaFile.builder(utils.getPackageString(utils.getClassFromKey(dependant)), genericInjectorBuilder.build()).build();
    try {
        javaFile.writeTo(processingEnv.getFiler());
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Also used : ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) TypeName(com.squareup.javapoet.TypeName) MethodSpec(com.squareup.javapoet.MethodSpec) TypeElement(javax.lang.model.element.TypeElement) ExecutableElement(javax.lang.model.element.ExecutableElement) VariableElement(javax.lang.model.element.VariableElement) TypeElement(javax.lang.model.element.TypeElement) ExecutableElement(javax.lang.model.element.ExecutableElement) Element(javax.lang.model.element.Element) IOException(java.io.IOException) TypeMirror(javax.lang.model.type.TypeMirror) Builder(com.squareup.javapoet.TypeSpec.Builder) JavaFile(com.squareup.javapoet.JavaFile) TypeSpec(com.squareup.javapoet.TypeSpec) DeclaredType(javax.lang.model.type.DeclaredType)

Example 27 with JavaFile

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

the class CoreInjectorGenerator method generateLockHolder.

private void generateLockHolder() {
    TypeSpec.Builder builder = TypeSpec.classBuilder(LOCK_HOLDER_CLASS_STRING).addModifiers(Modifier.PUBLIC).addField(FieldSpec.builder(ClassName.get(Lock.class), LOCK_HOLDER_FIELD_STRIN, Modifier.PUBLIC, Modifier.STATIC).initializer("new $T()", ClassName.get(ReentrantLock.class)).build());
    JavaFile javaFile = JavaFile.builder(LOCK_HOLDER_PACKAGE_STRING, builder.build()).build();
    try {
        javaFile.writeTo(processingEnv.getFiler());
    } catch (IOException e) {
        Throwables.propagate(e);
    }
}
Also used : ReentrantLock(java.util.concurrent.locks.ReentrantLock) Builder(com.squareup.javapoet.TypeSpec.Builder) JavaFile(com.squareup.javapoet.JavaFile) IOException(java.io.IOException) TypeSpec(com.squareup.javapoet.TypeSpec)

Example 28 with JavaFile

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

the class GeneralInjectorGenerator4 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(), javaFile.toString());
        javaFile.writeTo(processingEnv.getFiler());
    } catch (IOException e) {
        logger.e(e.toString());
    }
}
Also used : JavaFile(com.squareup.javapoet.JavaFile) IOException(java.io.IOException)

Example 29 with JavaFile

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

the class HubInjectorGenerator4 method generateGenericInjectorIfNeeded.

private void generateGenericInjectorIfNeeded(DependencyInfo dependencyInfo) {
    BindingKey dependant = dependencyInfo.getDependant();
    if (!generatedGenericInjectors.add(utils.getGenericInjectorName(dependant))) {
        return;
    }
    Builder genericInjectorBuilder = TypeSpec.classBuilder(utils.getGenericInjectorSimpleName(dependant)).addAnnotation(AnnotationSpec.builder(Generated.class).addMember("value", "$S", GENERATOR_NAME).build()).addModifiers(Modifier.PUBLIC);
    TypeName returnType = dependant.getTypeName();
    MethodSpec.Builder generateBuilder = MethodSpec.methodBuilder("generate").addModifiers(Modifier.PUBLIC).returns(returnType);
    for (BindingKey key : utils.sortBindingKeys(dependencyInfo.getDependencies())) {
        generateBuilder.addParameter(key.getTypeName(), utils.getSourceCodeName(key));
    }
    DeclaredType type = (DeclaredType) utils.getTypeFromTypeName(returnType);
    TypeElement classElement = (TypeElement) type.asElement();
    ExecutableElement ctor = Preconditions.checkNotNull(utils.findInjectedCtor(classElement), "injector ctor not found for dI: " + dependencyInfo);
    TypeMirror ctorTypeMirror = types.asMemberOf(type, ctor);
    List<BindingKey> ctorDependencies = utils.getCtorDependencies(dependencies, dependant);
    StringBuilder statementBuilder = new StringBuilder("$T result = new $T(");
    for (BindingKey key : ctorDependencies) {
        statementBuilder.append(utils.getSourceCodeName(key)).append(", ");
    }
    utils.trimTrailing(statementBuilder, ", ");
    statementBuilder.append(")");
    generateBuilder.addStatement(statementBuilder.toString(), returnType, returnType);
    for (Element element : classElement.getEnclosedElements()) {
        if (element.getKind().equals(ElementKind.FIELD) && utils.isInjected(element)) {
            generateBuilder.addStatement("result.$N = $L", element.getSimpleName(), utils.getSourceCodeName(utils.getKeyForField(type, element)));
        }
        if (element.getKind().equals(ElementKind.METHOD) && utils.isInjected(element)) {
            statementBuilder = new StringBuilder("result.$L(");
            for (BindingKey key : utils.getDependenciesFromMethod((ExecutableType) types.asMemberOf(type, element), (ExecutableElement) element)) {
                statementBuilder.append(utils.getSourceCodeName(key)).append(", ");
            }
            utils.trimTrailing(statementBuilder, ", ");
            statementBuilder.append(")");
            generateBuilder.addStatement(statementBuilder.toString(), element.getSimpleName());
        }
    }
    generateBuilder.addStatement("return result");
    genericInjectorBuilder.addMethod(generateBuilder.build());
    JavaFile javaFile = JavaFile.builder(utils.getPackageString(utils.getClassFromKey(dependant)), genericInjectorBuilder.build()).build();
    try {
        javaFile.writeTo(processingEnv.getFiler());
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Also used : ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) TypeName(com.squareup.javapoet.TypeName) MethodSpec(com.squareup.javapoet.MethodSpec) TypeElement(javax.lang.model.element.TypeElement) Builder(com.squareup.javapoet.TypeSpec.Builder) ExecutableElement(javax.lang.model.element.ExecutableElement) TypeElement(javax.lang.model.element.TypeElement) ExecutableElement(javax.lang.model.element.ExecutableElement) Element(javax.lang.model.element.Element) IOException(java.io.IOException) TypeMirror(javax.lang.model.type.TypeMirror) JavaFile(com.squareup.javapoet.JavaFile) DeclaredType(javax.lang.model.type.DeclaredType)

Example 30 with JavaFile

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

the class NewInjectorGenerator method generateTopLevelInjectors.

private void generateTopLevelInjectors() {
    SetMultimap<NewBindingKey, ClassName> keyToPackagedInjectorMap = Utils.reverseSetMultimap(generatedBindingsForPackagedInjector);
    // messager.printMessage(Kind.NOTE,
    // "generatedBindingsForPackagedInjector: " + generatedBindingsForPackagedInjector);
    // messager.printMessage(Kind.NOTE, "keyToPackagedInjectorMap: " + keyToPackagedInjectorMap);
    Set<ClassName> topLevelInjectedClassNames = new HashSet<>();
    for (ComponentInfo component : orderedComponents) {
        TypeSpec.Builder injectorBuilder = TypeSpec.classBuilder(getTopLevelInjectorName(component)).addAnnotation(AnnotationSpec.builder(Generated.class).addMember("value", "$S", GENERATOR_NAME).build()).addModifiers(Modifier.PUBLIC);
        // Member injector interfaces.
        for (TypeElement injector : memberInjectors.get(component)) {
            injectorBuilder.addSuperinterface(TypeName.get(injector.asType()));
        }
        MethodSpec.Builder ctorBuilder = MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC);
        // Containing top level injector.
        String containingInjectorName = "containingInjector";
        if (componentTree.get(component) != null) {
            ClassName containingInjectorClassName = ClassName.get(topLevelPackageString, getTopLevelInjectorName(componentTree.get(component)));
            injectorBuilder.addField(containingInjectorClassName, containingInjectorName, Modifier.PRIVATE);
            ctorBuilder.addParameter(containingInjectorClassName, containingInjectorName).addStatement("this.$L = $L", containingInjectorName, containingInjectorName);
        }
        // Passed modules.
        Set<TypeElement> allPassedModules = new HashSet<>();
        allPassedModules.addAll(nonNullaryCtorModules.get(component));
        allPassedModules.addAll(nonNullaryCtorUnscopedModules);
        for (TypeElement passedModule : Utils.sortByFullName(allPassedModules)) {
            String moduleName = Utils.getSourceCodeName(passedModule);
            ClassName moduleTypeName = (ClassName) TypeName.get(passedModule.asType());
            ctorBuilder.addParameter(moduleTypeName, moduleName).addStatement("this.$N = $N", moduleName, moduleName);
            injectorBuilder.addField(moduleTypeName, moduleName, Modifier.PRIVATE).addMethod(MethodSpec.methodBuilder(Utils.getGetMethodName(moduleTypeName)).addModifiers(Modifier.PUBLIC).returns(moduleTypeName).addStatement("return $N", moduleName).build());
        }
        injectorBuilder.addMethod(ctorBuilder.build());
        // Injection methods and non-injection methods.
        Set<String> miscMethodNames = new HashSet<>();
        Set<TypeElement> allMembersInjectors = Sets.newHashSet(memberInjectors.get(component));
        while (!allMembersInjectors.isEmpty()) {
            TypeElement injector = Iterables.getFirst(allMembersInjectors, null);
            Preconditions.checkNotNull(injector, String.format("Empty allMembersInjector."));
            allMembersInjectors.remove(injector);
            for (TypeMirror parentInterface : injector.getInterfaces()) {
                allMembersInjectors.add((TypeElement) ((DeclaredType) parentInterface).asElement());
            }
            for (Element element : injector.getEnclosedElements()) {
                if (!element.getKind().equals(ElementKind.METHOD)) {
                    continue;
                }
                // Injection methods.
                if (Utils.isInjectionMethod(element)) {
                    ExecutableElement method = (ExecutableElement) element;
                    TypeMirror typeMirror = Iterables.getOnlyElement(method.getParameters()).asType();
                    if (typeMirror.getKind().equals(TypeKind.TYPEVAR)) {
                        // TODO(freeman): support generic injection method.
                        continue;
                    }
                    TypeElement cls = (TypeElement) ((DeclaredType) typeMirror).asElement();
                    if (!topLevelInjectedClassNames.add(ClassName.get(cls))) {
                        continue;
                    }
                    ClassName packagedInjectorClassName = getPackagedInjectorNameOfScope(Utils.getPackageString(cls), component.getScope());
                    injectorBuilder.addMethod(MethodSpec.methodBuilder(method.getSimpleName().toString()).addModifiers(Modifier.PUBLIC).addParameter(ClassName.get(cls), "arg").addStatement("$L().inject(arg)", Utils.getGetMethodName(packagedInjectorClassName)).build());
                } else if (Utils.isProvisionMethodInInjector(element)) {
                    // non-injection methods, provision methods or getSubComponent method in
                    // editors. NOTE(freeman): subcomponent should be converted to component.
                    ExecutableElement method = (ExecutableElement) element;
                    if (!miscMethodNames.add(method.getSimpleName().toString())) {
                        continue;
                    }
                    MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(method.getSimpleName().toString()).addModifiers(Modifier.PUBLIC).returns(TypeName.get(method.getReturnType()));
                    NewBindingKey providedKey = Utils.getKeyProvidedByMethod(method);
                    ClassName packagedInjectorClassName = null;
                    for (ClassName className : keyToPackagedInjectorMap.get(providedKey)) {
                        if (isInjectorOfScope(className, component.getScope())) {
                            packagedInjectorClassName = className;
                            break;
                        }
                    }
                    if (packagedInjectorClassName == null) {
                        messager.printMessage(Kind.WARNING, String.format("PackagedInjector or multiBindingInjector not found for key: %s " + "from provisionMethod: %s. Probably it is not used.", providedKey, method));
                        // Create a dumb method
                        String statement = "return ";
                        TypeKind typeKind = method.getReturnType().getKind();
                        if (typeKind.equals(TypeKind.BOOLEAN)) {
                            statement += "false";
                        } else if (typeKind.equals(TypeKind.CHAR)) {
                            statement += "\'0\'";
                        } else if (typeKind.isPrimitive()) {
                            statement += "0";
                        } else {
                            statement += "null";
                        }
                        methodBuilder.addStatement(statement);
                    } else {
                        String statement = "return $L().$L()";
                        methodBuilder.addStatement(statement, Utils.getGetMethodName(packagedInjectorClassName), getProvisionMethodName(providedKey));
                    }
                    // System.out.println("provision method added: " + methodBuilder.build());
                    injectorBuilder.addMethod(methodBuilder.build());
                } else {
                    messager.printMessage(Kind.WARNING, String.format("Element %s ignored from injector %s.", element, injector));
                }
            }
        }
        // Methods to get injectors.
        for (Map.Entry<ClassName, TypeSpec.Builder> entry : packagedInjectorBuilders.entrySet()) {
            ClassName injectorClassName = entry.getKey();
            if (!component.equals(getComponentFromPackagedInjectorClassName(injectorClassName))) {
                continue;
            }
            String packagedInjectorSourceCodeName = Utils.getSourceCodeName(injectorClassName);
            injectorBuilder.addField(injectorClassName, packagedInjectorSourceCodeName, Modifier.PRIVATE);
            MethodSpec.Builder methodSpecBuilder = MethodSpec.methodBuilder(Utils.getGetMethodName(injectorClassName)).addModifiers(Modifier.PUBLIC).returns(injectorClassName).addStatement("$T result = $N", injectorClassName, packagedInjectorSourceCodeName).beginControlFlow("if (result == null)");
            StringBuilder stringBuilder = new StringBuilder("result = $N = new $T(this");
            if (componentTree.get(component) != null) {
                ClassName containingPackageInjectorClassName = getInjectorNameOfScope(injectorClassName, componentTree.get(component).getScope());
                stringBuilder.append(", ").append(containingInjectorName).append(".").append(Utils.getGetMethodName(containingPackageInjectorClassName)).append("()");
            }
            stringBuilder.append(")");
            methodSpecBuilder.addStatement(stringBuilder.toString(), packagedInjectorSourceCodeName, injectorClassName);
            methodSpecBuilder.endControlFlow().addStatement("return result");
            injectorBuilder.addMethod(methodSpecBuilder.build());
        }
        generateInjectorBuilder(component, injectorBuilder);
        JavaFile javaFile = JavaFile.builder(topLevelPackageString, injectorBuilder.build()).build();
        try {
            javaFile.writeTo(processingEnv.getFiler());
        } catch (IOException e) {
            Throwables.propagate(e);
        }
    }
}
Also used : PackageElement(javax.lang.model.element.PackageElement) 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) Builder(com.squareup.javapoet.TypeSpec.Builder) TypeKind(javax.lang.model.type.TypeKind) TypeMirror(javax.lang.model.type.TypeMirror) Builder(com.squareup.javapoet.TypeSpec.Builder) ClassName(com.squareup.javapoet.ClassName) HashSet(java.util.HashSet) MethodSpec(com.squareup.javapoet.MethodSpec) TypeElement(javax.lang.model.element.TypeElement) IOException(java.io.IOException) JavaFile(com.squareup.javapoet.JavaFile) HashMap(java.util.HashMap) Map(java.util.Map) TypeSpec(com.squareup.javapoet.TypeSpec) DeclaredType(javax.lang.model.type.DeclaredType)

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