Search in sources :

Example 31 with TypeDef

use of io.sundr.model.TypeDef in project sundrio by sundrio.

the class AbstractBuilderProcessor method generateBuildables.

public void generateBuildables(BuilderContext ctx, Set<TypeDef> buildables) {
    int total = ctx.getBuildableRepository().getBuildables().size();
    int count = 0;
    for (TypeDef typeDef : buildables) {
        RichTypeDef richTypeDef = TypeArguments.apply(typeDef);
        double percentage = 100d * (count++) / total;
        if (typeDef.isInterface() || typeDef.isAnnotation()) {
            continue;
        }
        System.err.printf("\033[2K%3d%% Generating: %s\r", Math.round(percentage), typeDef.getFullyQualifiedName());
        generate(ClazzAs.FLUENT_INTERFACE.apply(richTypeDef));
        generate(ClazzAs.FLUENT_IMPL.apply(richTypeDef));
        if (typeDef.isAbstract()) {
            continue;
        }
        if (!typeDef.isFinal() && typeDef.getAttributes().containsKey(EDITABLE_ENABLED) && (Boolean) typeDef.getAttributes().get(EDITABLE_ENABLED)) {
            generate(ClazzAs.EDITABLE_BUILDER.apply(richTypeDef));
            generate(ClazzAs.EDITABLE.apply(richTypeDef));
        } else {
            generate(ClazzAs.BUILDER.apply(richTypeDef));
        }
        Buildable buildable = typeDef.getAttribute(BUILDABLE);
        ExternalBuildables externalBuildables = typeDef.getAttribute(EXTERNAL_BUILDABLE);
        if (buildable != null) {
            for (final Inline inline : buildable.inline()) {
                generate(inlineableOf(ctx, typeDef, inline));
            }
        } else if (externalBuildables != null) {
            for (final Inline inline : externalBuildables.inline()) {
                generate(inlineableOf(ctx, typeDef, inline));
            }
        }
    }
}
Also used : RichTypeDef(io.sundr.model.RichTypeDef) TypeDef(io.sundr.model.TypeDef) ExternalBuildables(io.sundr.builder.annotations.ExternalBuildables) Inline(io.sundr.builder.annotations.Inline) Buildable(io.sundr.builder.annotations.Buildable) RichTypeDef(io.sundr.model.RichTypeDef)

Example 32 with TypeDef

use of io.sundr.model.TypeDef in project sundrio by sundrio.

the class AbstractBuilderProcessor method inlineableOf.

static TypeDef inlineableOf(BuilderContext ctx, TypeDef type, Inline inline) {
    final String inlineableName = !inline.name().isEmpty() ? inline.name() : inline.prefix() + type.getName() + inline.suffix();
    List<Method> constructors = new ArrayList<Method>();
    final TypeDef builderType = TypeAs.BUILDER.apply(type);
    TypeDef inlineType = BuilderUtils.getInlineType(ctx, inline);
    TypeDef returnType = BuilderUtils.getInlineReturnType(ctx, inline, type);
    final ClassRef inlineTypeRef = inlineType.toReference(returnType.toReference());
    // Use the builder as the base of the inlineable. Just add interface and change name.
    final TypeDef shallowInlineType = new TypeDefBuilder(builderType).withName(inlineableName).withImplementsList(inlineTypeRef).withProperties().withMethods().withConstructors().build();
    TypeRef functionType = Constants.FUNCTION.toReference(type.toInternalReference(), returnType.toInternalReference());
    Property builderProperty = new PropertyBuilder().withTypeRef(TypeAs.BUILDER.apply(type).toInternalReference()).withName(BUILDER).withModifiers(Types.modifiersToInt(Modifier.PRIVATE, Modifier.FINAL)).build();
    Property functionProperty = new PropertyBuilder().withTypeRef(functionType).withName(FUNCTION).withModifiers(Types.modifiersToInt(Modifier.PRIVATE, Modifier.FINAL)).build();
    Method inlineMethod = new MethodBuilder().withReturnType(returnType.toInternalReference()).withName(inline.value()).withNewBlock().addNewStringStatementStatement(BUILD_AND_APPLY_FUNCTION).endBlock().withModifiers(Types.modifiersToInt(Modifier.PUBLIC)).build();
    constructors.add(new MethodBuilder().withReturnType(inlineTypeRef).withName(EMPTY).addNewArgument().withName(FUNCTION).withTypeRef(functionType).and().withModifiers(Types.modifiersToInt(Modifier.PUBLIC)).withNewBlock().addNewStringStatementStatement(String.format(NEW_BULDER_AND_SET_FUNCTION_FORMAT, builderType.getName())).endBlock().build());
    constructors.add(new MethodBuilder().withReturnType(inlineTypeRef).withName(EMPTY).addNewArgument().withName(ITEM).withTypeRef(type.toInternalReference()).and().addNewArgument().withName(FUNCTION).withTypeRef(functionType).and().withModifiers(Types.modifiersToInt(Modifier.PUBLIC)).withNewBlock().addNewStringStatementStatement(String.format(NEW_BULDER_WITH_ITEM_AND_SET_FUNCTION_FORMAT, builderType.getName())).endBlock().build());
    if (type.equals(returnType)) {
        constructors.add(new MethodBuilder().withReturnType(inlineTypeRef).withName(EMPTY).addNewArgument().withName(ITEM).withTypeRef(type.toInternalReference()).and().withModifiers(Types.modifiersToInt(Modifier.PUBLIC)).withNewBlock().addNewStringStatementStatement(String.format(NEW_BUILDER_AND_EMTPY_FUNCTION_FORMAT, builderType.getName(), String.format(EMPTY_FUNCTION_TEXT, type.toInternalReference(), returnType.toInternalReference(), returnType.toInternalReference(), type.toInternalReference()))).endBlock().build());
    }
    return new TypeDefBuilder(shallowInlineType).withAnnotations().withModifiers(Types.modifiersToInt(Modifier.PUBLIC)).withConstructors(constructors).addToProperties(builderProperty, functionProperty).addToMethods(inlineMethod).accept(new TypedVisitor<ClassRefBuilder>() {

        @Override
        public void visit(ClassRefBuilder builder) {
            List<TypeRef> updatedArguments = new ArrayList<TypeRef>();
            for (TypeRef arg : builder.getArguments()) {
                if (arg.equals(builderType.toInternalReference())) {
                    updatedArguments.add(shallowInlineType.toInternalReference());
                } else {
                    updatedArguments.add(arg);
                }
            }
            builder.withArguments(updatedArguments);
        }
    }).build();
}
Also used : TypedVisitor(io.sundr.builder.TypedVisitor) ClassRef(io.sundr.model.ClassRef) TypeRef(io.sundr.model.TypeRef) ClassRefBuilder(io.sundr.model.ClassRefBuilder) ArrayList(java.util.ArrayList) Method(io.sundr.model.Method) TypeDefBuilder(io.sundr.model.TypeDefBuilder) MethodBuilder(io.sundr.model.MethodBuilder) RichTypeDef(io.sundr.model.RichTypeDef) TypeDef(io.sundr.model.TypeDef) Property(io.sundr.model.Property) PropertyBuilder(io.sundr.model.PropertyBuilder)

Example 33 with TypeDef

use of io.sundr.model.TypeDef in project sundrio by sundrio.

the class Combine method canBeExcluded.

private static boolean canBeExcluded(TypeDef candidate, Iterable<TypeDef> provided) {
    Set<TypeDef> allOther = new LinkedHashSet<TypeDef>();
    for (TypeDef c : provided) {
        if (!c.equals(candidate)) {
            allOther.add(c);
        }
    }
    Set<ClassRef> allProvided = TypeDefUtils.extractInterfacesFromTypes(allOther);
    for (ClassRef type : TypeDefUtils.extractInterfacesFromType(candidate)) {
        if (!allProvided.contains(type)) {
            return false;
        }
    }
    return true;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) TypeDef(io.sundr.model.TypeDef) ClassRef(io.sundr.model.ClassRef)

Example 34 with TypeDef

use of io.sundr.model.TypeDef in project sundrio by sundrio.

the class TypeDefUtils method executablesToInterfaces.

/**
 * Convert a {@link Collection} of {@link javax.lang.model.element.ExecutableElement}s to a {@link java.util.Set} of
 * {@link io.sundr.model.TypeDef}es.
 *
 * @param context The context of the operation.
 * @param elements The target elements.
 * @return A set of {@link io.sundr.model.TypeDef} that describes the interfaces.
 */
public static Set<TypeDef> executablesToInterfaces(DslContext context, Collection<ExecutableElement> elements) {
    Map<String, TypeDef> byName = new LinkedHashMap<String, TypeDef>();
    for (ExecutableElement current : elements) {
        TypeDef clazz = executableToInterface(context, current);
        InterfaceName interfaceName = current.getAnnotation(InterfaceName.class);
        String name = interfaceName != null ? clazz.getPackageName() + "." + interfaceName.value() : clazz.getFullyQualifiedName();
        if (byName.containsKey(name)) {
            TypeDef other = byName.remove(name);
            byName.put(name, Merge.CLASSES.apply(new TypeDef[] { other, clazz }));
        } else {
            byName.put(name, clazz);
        }
    }
    return new LinkedHashSet<TypeDef>(byName.values());
}
Also used : LinkedHashSet(java.util.LinkedHashSet) TypeDef(io.sundr.model.TypeDef) ExecutableElement(javax.lang.model.element.ExecutableElement) InterfaceName(io.sundr.dsl.annotations.InterfaceName) LinkedHashMap(java.util.LinkedHashMap)

Example 35 with TypeDef

use of io.sundr.model.TypeDef in project sundrio by sundrio.

the class ClazzAs method staticAdapterBody.

private static String staticAdapterBody(TypeDef pojo, TypeDef pojoBuilder, TypeDef source, boolean returnBuilder) {
    StringBuilder sb = new StringBuilder();
    sb.append("return new ").append(pojoBuilder.getName()).append("()");
    for (Method m : source.getMethods()) {
        String trimmedName = Strings.deCapitalizeFirst(m.getName().replaceAll("^get", "").replaceAll("^is", ""));
        if (m.getReturnType() instanceof ClassRef) {
            ClassRef ref = (ClassRef) m.getReturnType();
            Boolean hasSuperClass = pojo.getProperties().stream().filter(p -> p.getTypeRef() instanceof ClassRef && p.getName().equals(Getter.propertyNameSafe(m))).map(p -> GetDefinition.of((ClassRef) p.getTypeRef())).flatMap(c -> c.getExtendsList().stream()).count() > 0;
            if (GetDefinition.of(ref).isAnnotation()) {
                TypeDef generatedType = Types.allProperties(pojo).stream().filter(p -> p.getName().equals(m.getName())).map(p -> p.getTypeRef()).filter(r -> r instanceof ClassRef).map(r -> (ClassRef) r).map(c -> GetDefinition.of(c)).findFirst().orElse(null);
                if (generatedType != null) {
                    Method ctor = BuilderUtils.findBuildableConstructor(generatedType);
                    if (m.getReturnType().getDimensions() > 0) {
                        sb.append(".addAllTo").append(Strings.capitalizeFirst(trimmedName)).append("(").append("Arrays.asList(").append("instance.").append(m.getName()).append("())").append(".stream().map(i ->").append("new ").append(generatedType.getName()).append("(").append(ctor.getArguments().stream().map(p -> Getter.find(GetDefinition.of((ClassRef) m.getReturnType()), p, true)).map(g -> g.getName()).map(s -> "i." + s + "()").collect(Collectors.joining(", "))).append(")").append(")").append(".collect(Collectors.toList()))");
                    } else {
                        sb.append(".with").append(Strings.capitalizeFirst(trimmedName)).append("(").append("new ").append(generatedType.getName()).append("(").append(ctor.getArguments().stream().map(p -> Getter.find(GetDefinition.of((ClassRef) m.getReturnType()), p, true)).map(g -> g.getName()).map(s -> "instance." + m.getName() + "()." + s + "()").collect(Collectors.joining(", "))).append(")").append(")");
                    }
                    continue;
                }
            }
        }
        String withMethod = "with" + (Strings.capitalizeFirst(trimmedName));
        if (Types.hasProperty(pojo, trimmedName)) {
            sb.append(".").append(withMethod).append("(").append("instance.").append(m.getName()).append("())");
        }
    }
    if (returnBuilder) {
        sb.append(".build();");
    } else {
        sb.append(";");
    }
    return sb.toString();
}
Also used : FunctionFactory(io.sundr.FunctionFactory) StringStatement(io.sundr.model.StringStatement) Modifier(javax.lang.model.element.Modifier) Buildable(io.sundr.builder.annotations.Buildable) TypeParamRef(io.sundr.model.TypeParamRef) GetDefinition(io.sundr.model.functions.GetDefinition) TypeDefBuilder(io.sundr.model.TypeDefBuilder) Function(java.util.function.Function) Supplier(java.util.function.Supplier) BuilderUtils(io.sundr.builder.internal.utils.BuilderUtils) ArrayList(java.util.ArrayList) ClassRef(io.sundr.model.ClassRef) Getter(io.sundr.model.utils.Getter) InitEnricher(io.sundr.builder.internal.visitors.InitEnricher) Map(java.util.Map) RichTypeDef(io.sundr.model.RichTypeDef) Types(io.sundr.model.utils.Types) Constants(io.sundr.builder.Constants) AptContext(io.sundr.adapter.apt.AptContext) Strings(io.sundr.utils.Strings) TypedVisitor(io.sundr.builder.TypedVisitor) BuilderContext(io.sundr.builder.internal.BuilderContext) SundrException(io.sundr.SundrException) Set(java.util.Set) Method(io.sundr.model.Method) TypeRef(io.sundr.model.TypeRef) Types.isAbstract(io.sundr.model.utils.Types.isAbstract) Setter(io.sundr.model.utils.Setter) AnnotationRef(io.sundr.model.AnnotationRef) Collectors(java.util.stream.Collectors) Property(io.sundr.model.Property) List(java.util.List) ClassRefBuilder(io.sundr.model.ClassRefBuilder) MethodBuilder(io.sundr.model.MethodBuilder) TypeArguments(io.sundr.model.utils.TypeArguments) Statement(io.sundr.model.Statement) TypeDef(io.sundr.model.TypeDef) Optional(java.util.Optional) PropertyBuilder(io.sundr.model.PropertyBuilder) BuilderContextManager(io.sundr.builder.internal.BuilderContextManager) TypeParamDef(io.sundr.model.TypeParamDef) ClassRef(io.sundr.model.ClassRef) RichTypeDef(io.sundr.model.RichTypeDef) TypeDef(io.sundr.model.TypeDef) Method(io.sundr.model.Method)

Aggregations

TypeDef (io.sundr.model.TypeDef)99 ClassRef (io.sundr.model.ClassRef)43 Test (org.junit.Test)40 RichTypeDef (io.sundr.model.RichTypeDef)38 TypeDefBuilder (io.sundr.model.TypeDefBuilder)35 TypeRef (io.sundr.model.TypeRef)26 Method (io.sundr.model.Method)22 Property (io.sundr.model.Property)22 ArrayList (java.util.ArrayList)20 List (java.util.List)15 TypeElement (javax.lang.model.element.TypeElement)15 Collectors (java.util.stream.Collectors)14 Element (javax.lang.model.element.Element)14 Set (java.util.Set)12 Test (org.junit.jupiter.api.Test)12 AnnotationRef (io.sundr.model.AnnotationRef)11 DefinitionRepository (io.sundr.model.repo.DefinitionRepository)11 HashMap (java.util.HashMap)11 AptContext (io.sundr.adapter.apt.AptContext)10 ClassRefBuilder (io.sundr.model.ClassRefBuilder)10