Search in sources :

Example 21 with TypeSpec

use of com.squareup.javapoet.TypeSpec in project glide by bumptech.

the class ModuleAnnotationProcessor method process.

/**
   * Each round we do the following:
   * <ol>
   *   <li>Find all RootGlideModules and save them to an instance variable (throw if > 1).
   *   <li>Find all ChildGlideModules
   *   <li>For each ChildGlideModule, write an Indexer with an Annotation with the class name.
   *   <li>If we wrote any Indexers, return and wait for the next round.
   *   <li>If we didn't write any Indexers and there is a RootGlideModule, write the
   *   GeneratedRootGlideModule. Once the GeneratedRootGlideModule is written, we expect to be
   *   finished. Any further generation of related classes will result in errors.
   * </ol>
   */
@Override
public boolean process(Set<? extends TypeElement> set, RoundEnvironment env) {
    round++;
    // Order matters here, if we find an Indexer below, we return before writing the root module. If
    // we fail to add to rootModules before then, we might accidentally skip a valid RootModule.
    List<TypeElement> childGlideModules = new ArrayList<>();
    for (TypeElement element : getElementsFor(GlideModule.class, env)) {
        if (processingEnv.getTypeUtils().isAssignable(element.asType(), rootGlideModuleType.asType())) {
            rootGlideModules.add(element);
        } else if (processingEnv.getTypeUtils().isAssignable(element.asType(), childGlideModuleType.asType())) {
            childGlideModules.add(element);
        } else {
            throw new IllegalStateException("@GlideModule can only be applied to ChildGlideModule" + " and RootGlideModule implementations, not: " + element);
        }
    }
    debugLog("got child modules: " + childGlideModules);
    debugLog("got root modules: " + rootGlideModules);
    if (rootGlideModules.size() > 1) {
        throw new IllegalStateException("You cannot have more than one RootGlideModule, found: " + rootGlideModules);
    }
    if (!childGlideModules.isEmpty()) {
        if (isGeneratedRootGlideModuleWritten) {
            throw new IllegalStateException("Cannot process ChildModules after writing RootModules: " + childGlideModules);
        }
        TypeSpec indexer = GlideIndexerGenerator.generate(childGlideModules);
        writeIndexer(indexer);
        debugLog("Wrote an Indexer this round, skipping the root module to ensure all indexers are" + " found");
        // and we can safely wait to write our RootModule until then.
        return true;
    }
    // most once.
    if (isGeneratedRootGlideModuleWritten || rootGlideModules.isEmpty()) {
        return false;
    }
    debugLog("Processing root module: " + rootGlideModules.iterator().next());
    // If this package is null, it means there are no classes with this package name. One way this
    // could happen is if we process an annotation and reach this point without writing something
    // to the package. We do not error check here because that shouldn't happen with the
    // current implementation.
    PackageElement glideGenPackage = processingEnv.getElementUtils().getPackageElement(COMPILER_PACKAGE_NAME);
    glideModuleClassNames.addAll(getGlideModuleClassNames(glideGenPackage));
    TypeSpec generatedRootGlideModule = RootModuleGenerator.generate(processingEnv, rootGlideModules.get(0).getQualifiedName().toString(), glideModuleClassNames);
    writeRootModule(generatedRootGlideModule);
    isGeneratedRootGlideModuleWritten = true;
    infoLog("Wrote GeneratedRootGlideModule with: " + glideModuleClassNames);
    return true;
}
Also used : TypeElement(javax.lang.model.element.TypeElement) ArrayList(java.util.ArrayList) PackageElement(javax.lang.model.element.PackageElement) TypeSpec(com.squareup.javapoet.TypeSpec)

Example 22 with TypeSpec

use of com.squareup.javapoet.TypeSpec in project LoganSquare by bluelinelabs.

the class ObjectMapperInjector method getTypeSpec.

private TypeSpec getTypeSpec() {
    TypeSpec.Builder builder = TypeSpec.classBuilder(mJsonObjectHolder.injectedClassName).addModifiers(Modifier.PUBLIC, Modifier.FINAL);
    builder.addAnnotation(AnnotationSpec.builder(SuppressWarnings.class).addMember("value", "\"unsafe,unchecked\"").build());
    builder.superclass(ParameterizedTypeName.get(ClassName.get(JsonMapper.class), mJsonObjectHolder.objectTypeName));
    for (TypeParameterElement typeParameterElement : mJsonObjectHolder.typeParameters) {
        builder.addTypeVariable(TypeVariableName.get((TypeVariable) typeParameterElement.asType()));
    }
    if (mJsonObjectHolder.hasParentClass()) {
        FieldSpec.Builder parentMapperBuilder;
        if (mJsonObjectHolder.parentTypeParameters.size() == 0) {
            parentMapperBuilder = FieldSpec.builder(ParameterizedTypeName.get(ClassName.get(JsonMapper.class), mJsonObjectHolder.parentTypeName), PARENT_OBJECT_MAPPER_VARIABLE_NAME).addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL).initializer("$T.mapperFor($T.class)", LoganSquare.class, mJsonObjectHolder.parentTypeName);
        } else {
            parentMapperBuilder = FieldSpec.builder(ParameterizedTypeName.get(ClassName.get(JsonMapper.class), mJsonObjectHolder.getParameterizedParentTypeName()), PARENT_OBJECT_MAPPER_VARIABLE_NAME).addModifiers(Modifier.PRIVATE);
            if (mJsonObjectHolder.typeParameters.size() == 0) {
                parentMapperBuilder.initializer("$T.mapperFor(new $T<$T>() { })", LoganSquare.class, ParameterizedType.class, mJsonObjectHolder.getParameterizedParentTypeName());
            }
        }
        builder.addField(parentMapperBuilder.build());
    }
    // TypeConverters could be expensive to create, so just use one per class
    Set<ClassName> typeConvertersUsed = new HashSet<>();
    for (JsonFieldHolder fieldHolder : mJsonObjectHolder.fieldMap.values()) {
        if (fieldHolder.type instanceof TypeConverterFieldType) {
            typeConvertersUsed.add(((TypeConverterFieldType) fieldHolder.type).getTypeConverterClassName());
        }
    }
    for (ClassName typeConverter : typeConvertersUsed) {
        builder.addField(FieldSpec.builder(typeConverter, getStaticFinalTypeConverterVariableName(typeConverter)).addModifiers(Modifier.PROTECTED, Modifier.STATIC, Modifier.FINAL).initializer("new $T()", typeConverter).build());
    }
    MethodSpec.Builder constructorBuilder = MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC);
    List<String> createdJsonMappers = new ArrayList<>();
    if (mJsonObjectHolder.typeParameters.size() > 0) {
        constructorBuilder.addParameter(ClassName.get(ParameterizedType.class), "type");
        constructorBuilder.addStatement("partialMappers.put(type, this)");
        for (TypeParameterElement typeParameterElement : mJsonObjectHolder.typeParameters) {
            final String typeName = typeParameterElement.getSimpleName().toString();
            final String typeArgumentName = typeName + "Type";
            final String jsonMapperVariableName = getJsonMapperVariableNameForTypeParameter(typeName);
            if (!createdJsonMappers.contains(jsonMapperVariableName)) {
                createdJsonMappers.add(jsonMapperVariableName);
                // Add a JsonMapper reference
                builder.addField(FieldSpec.builder(ParameterizedTypeName.get(ClassName.get(JsonMapper.class), TypeVariableName.get(typeName)), jsonMapperVariableName).addModifiers(Modifier.PRIVATE, Modifier.FINAL).build());
                constructorBuilder.addParameter(ClassName.get(ParameterizedType.class), typeArgumentName);
                constructorBuilder.addStatement("$L = $T.mapperFor($L, partialMappers)", jsonMapperVariableName, LoganSquare.class, typeArgumentName);
            }
        }
        constructorBuilder.addParameter(ParameterizedTypeName.get(ClassName.get(SimpleArrayMap.class), ClassName.get(ParameterizedType.class), ClassName.get(JsonMapper.class)), "partialMappers");
    }
    for (JsonFieldHolder jsonFieldHolder : mJsonObjectHolder.fieldMap.values()) {
        if (jsonFieldHolder.type instanceof ParameterizedTypeField) {
            final String jsonMapperVariableName = getJsonMapperVariableNameForTypeParameter(((ParameterizedTypeField) jsonFieldHolder.type).getParameterName());
            if (!createdJsonMappers.contains(jsonMapperVariableName)) {
                ParameterizedTypeName parameterizedType = ParameterizedTypeName.get(ClassName.get(JsonMapper.class), jsonFieldHolder.type.getTypeName());
                createdJsonMappers.add(jsonMapperVariableName);
                builder.addField(FieldSpec.builder(parameterizedType, jsonMapperVariableName).addModifiers(Modifier.PRIVATE, Modifier.FINAL).build());
                String typeName = jsonMapperVariableName + "Type";
                constructorBuilder.addStatement("$T $L = new $T<$T>() { }", ParameterizedType.class, typeName, ParameterizedType.class, jsonFieldHolder.type.getTypeName());
                if (mJsonObjectHolder.typeParameters.size() > 0) {
                    constructorBuilder.beginControlFlow("if ($L.equals(type))", typeName);
                    constructorBuilder.addStatement("$L = ($T)this", jsonMapperVariableName, JsonMapper.class);
                    constructorBuilder.nextControlFlow("else");
                    constructorBuilder.addStatement("$L = $T.mapperFor($L, partialMappers)", jsonMapperVariableName, LoganSquare.class, typeName);
                    constructorBuilder.endControlFlow();
                } else {
                    constructorBuilder.addStatement("$L = $T.mapperFor($L)", jsonMapperVariableName, LoganSquare.class, typeName);
                }
            }
        }
    }
    if (createdJsonMappers.size() > 0) {
        if (mJsonObjectHolder.hasParentClass()) {
            constructorBuilder.addStatement("$L = $T.mapperFor(new $T<$T>() { })", PARENT_OBJECT_MAPPER_VARIABLE_NAME, LoganSquare.class, ParameterizedType.class, mJsonObjectHolder.getParameterizedParentTypeName());
        }
        builder.addMethod(constructorBuilder.build());
    }
    builder.addMethod(getParseMethod());
    builder.addMethod(getParseFieldMethod());
    builder.addMethod(getSerializeMethod());
    addUsedJsonMapperVariables(builder);
    addUsedTypeConverterMethods(builder);
    return builder.build();
}
Also used : MethodSpec(com.squareup.javapoet.MethodSpec) ParameterizedTypeField(com.bluelinelabs.logansquare.processor.type.field.ParameterizedTypeField) ArrayList(java.util.ArrayList) FieldSpec(com.squareup.javapoet.FieldSpec) TypeParameterElement(javax.lang.model.element.TypeParameterElement) JsonMapper(com.bluelinelabs.logansquare.JsonMapper) ParameterizedType(com.bluelinelabs.logansquare.ParameterizedType) TypeConverterFieldType(com.bluelinelabs.logansquare.processor.type.field.TypeConverterFieldType) TypeVariable(javax.lang.model.type.TypeVariable) LoganSquare(com.bluelinelabs.logansquare.LoganSquare) ClassName(com.squareup.javapoet.ClassName) TypeSpec(com.squareup.javapoet.TypeSpec) HashSet(java.util.HashSet) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName)

Example 23 with TypeSpec

use of com.squareup.javapoet.TypeSpec in project caffeine by ben-manes.

the class NodeFactoryGenerator method addEnumConstant.

private void addEnumConstant(String className, Set<Feature> features) {
    String statementWithKey = makeFactoryStatementKey();
    String statementWithKeyRef = makeFactoryStatementKeyRef();
    TypeSpec.Builder typeSpec = TypeSpec.anonymousClassBuilder("").addMethod(newNodeByKey().addStatement(statementWithKey, className).build()).addMethod(newNodeByKeyRef().addStatement(statementWithKeyRef, className).build());
    if (features.contains(Feature.WEAK_KEYS)) {
        typeSpec.addMethod(makeNewLookupKey());
        typeSpec.addMethod(makeReferenceKey());
    }
    nodeFactory.addEnumConstant(className, typeSpec.build());
}
Also used : AddToString(com.github.benmanes.caffeine.cache.node.AddToString) TypeSpec(com.squareup.javapoet.TypeSpec)

Example 24 with TypeSpec

use of com.squareup.javapoet.TypeSpec in project potato by eyeem.

the class CodeWriter method process.

private void process() throws ClassNotFoundException, IOException {
    // Build fields
    ArrayList<FieldSpec> fields = new ArrayList<>();
    FieldSpec field;
    //FieldSpec.builder(String.class, "instance", Modifier.PRIVATE, Modifier.STATIC);
    field = FieldSpec.builder(generatedClass, "instance").addModifiers(Modifier.PRIVATE, Modifier.STATIC).build();
    fields.add(field);
    // Build methods
    ArrayList<MethodSpec> methods = new ArrayList<>();
    MethodSpec method;
    method = MethodSpec.constructorBuilder().addModifiers(Modifier.PRIVATE).addParameter(context, "context").addStatement("super(context)").build();
    methods.add(method);
    method = MethodSpec.methodBuilder("id").addAnnotation(Override.class).addModifiers(Modifier.PUBLIC).addParameter(dataClass, "object").returns(String.class).addStatement("return object." + id).build();
    methods.add(method);
    method = MethodSpec.methodBuilder("classname").addAnnotation(Override.class).addModifiers(Modifier.PUBLIC).returns(Class.class).addStatement("return $T.class", dataClass).build();
    methods.add(method);
    method = MethodSpec.methodBuilder("get").addModifiers(Modifier.PUBLIC, Modifier.STATIC).addParameter(context, "context").returns(generatedClass).addStatement("if(instance == null) initialise(context)").addStatement("return instance").build();
    methods.add(method);
    method = MethodSpec.methodBuilder("initialise").addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.SYNCHRONIZED).addParameter(context, "context").beginControlFlow("if(instance == null)").addStatement("instance = new $T(context)", generatedClass).addStatement("instance.init()").endControlFlow().build();
    methods.add(method);
    // build class
    TypeSpec.Builder builder = TypeSpec.classBuilder(generatedClassName).addModifiers(Modifier.PUBLIC).superclass(ParameterizedTypeName.get(ClassName.get("com.eyeem.storage", "Storage"), dataClass));
    for (FieldSpec fieldSpec : fields) builder.addField(fieldSpec);
    for (MethodSpec methodSpec : methods) builder.addMethod(methodSpec);
    TypeSpec typeSpec = builder.build();
    JavaFile javaFile = JavaFile.builder(packageName, typeSpec).build();
    Writer writer = filer.createSourceFile(packageName + "." + generatedClassName).openWriter();
    javaFile.writeTo(writer);
    writer.close();
}
Also used : MethodSpec(com.squareup.javapoet.MethodSpec) ArrayList(java.util.ArrayList) JavaFile(com.squareup.javapoet.JavaFile) FieldSpec(com.squareup.javapoet.FieldSpec) Writer(java.io.Writer) TypeSpec(com.squareup.javapoet.TypeSpec)

Example 25 with TypeSpec

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

the class NewInjectorGenerator method createAnonymousBuiltinType.

/**
   * Generate for either unique a binding or a contributor to a multi-binding. NewDependencyInfo is
   * null for unique one and non-null or multi-binding one. ReferencingClass is the opposite, for
   * multi-binding, it is the module in dependency. Scope is null for unique binding.
   */
private TypeSpec createAnonymousBuiltinType(ClassName leafInjectorClassName, NewBindingKey key, @Nullable TypeElement scope, @Nullable TypeElement referencingClass, @Nullable NewDependencyInfo newDependencyInfo) {
    Preconditions.checkArgument(key.getTypeName() instanceof ParameterizedTypeName);
    boolean isMultiBinding = newDependencyInfo != null;
    if (isMultiBinding) {
        Preconditions.checkArgument(referencingClass == null);
        Preconditions.checkNotNull(scope);
    } else {
        Preconditions.checkNotNull(referencingClass);
    }
    TypeName rawTypeName = ((ParameterizedTypeName) key.getTypeName()).rawType;
    Preconditions.checkArgument(Utils.hasBuiltinBinding(key), String.format("Built-in binding expected(Provider or Lazy), but get %s", key));
    boolean isLazy = rawTypeName.equals(ClassName.get(Lazy.class));
    NewBindingKey elementKey = Utils.getElementKeyForBuiltinBinding(key);
    Preconditions.checkNotNull(elementKey);
    if (!isMultiBinding) {
        generateProvisionMethodIfNeeded(elementKey, referencingClass);
    }
    MethodSpec.Builder builderForGet = MethodSpec.methodBuilder("get").returns(elementKey.getTypeName()).addAnnotation(Override.class).addModifiers(Modifier.PUBLIC);
    builderForGet.addStatement("$T var = null", elementKey.getTypeName());
    if (isLazy) {
        builderForGet.beginControlFlow("if (var == null)");
    }
    if (!isMultiBinding) {
        builderForGet.addStatement("var = $N()", getProvisionMethodName(elementKey));
    } else {
        addNewStatementToMethodSpec(scope, newDependencyInfo, leafInjectorClassName, builderForGet, "var");
    }
    if (isLazy) {
        builderForGet.endControlFlow();
    }
    builderForGet.addStatement("return var");
    TypeSpec result = TypeSpec.anonymousClassBuilder("").addSuperinterface(key.getTypeName()).addMethod(builderForGet.build()).build();
    return result;
}
Also used : Lazy(dagger.Lazy) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) TypeName(com.squareup.javapoet.TypeName) MethodSpec(com.squareup.javapoet.MethodSpec) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) TypeSpec(com.squareup.javapoet.TypeSpec)

Aggregations

TypeSpec (com.squareup.javapoet.TypeSpec)44 ClassName (com.squareup.javapoet.ClassName)26 MethodSpec (com.squareup.javapoet.MethodSpec)20 ParameterizedTypeName (com.squareup.javapoet.ParameterizedTypeName)10 TypeName (com.squareup.javapoet.TypeName)8 NotNull (org.jetbrains.annotations.NotNull)8 FieldSpec (com.squareup.javapoet.FieldSpec)7 ArrayList (java.util.ArrayList)6 Type (com.squareup.wire.schema.Type)5 TypeElement (javax.lang.model.element.TypeElement)5 ByteString (okio.ByteString)5 WireField (com.squareup.wire.WireField)4 JavaGenerator (com.squareup.wire.java.JavaGenerator)4 Field (com.squareup.wire.schema.Field)4 MessageType (com.squareup.wire.schema.MessageType)4 ProtoType (com.squareup.wire.schema.ProtoType)4 Schema (com.squareup.wire.schema.Schema)4 CodeBlock (com.squareup.javapoet.CodeBlock)3 EnclosingType (com.squareup.wire.schema.EnclosingType)3 EnumType (com.squareup.wire.schema.EnumType)3