Search in sources :

Example 16 with TypeRef

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

the class ToPojo method getDefaultValue.

private static String getDefaultValue(Attributeable attributeable) {
    Object value = attributeable.getAttribute(DEFAULT_VALUE);
    String stringVal = value != null ? String.valueOf(value) : null;
    TypeRef typeRef = null;
    if (attributeable instanceof Method) {
        typeRef = ((Method) attributeable).getReturnType();
    } else if (attributeable instanceof Property) {
        typeRef = ((Property) attributeable).getTypeRef();
    } else {
        throw new IllegalArgumentException("Method 'getDefaultValue' accepts Property or Method as argument!");
    }
    if (typeRef.getDimensions() > 0) {
        StringBuilder sb = new StringBuilder();
        if (typeRef instanceof PrimitiveRef) {
            sb.append(((PrimitiveRef) typeRef).getName());
        } else if (typeRef instanceof ClassRef) {
            sb.append("new ").append(((ClassRef) typeRef).getFullyQualifiedName());
        }
        for (int d = 0; d < typeRef.getDimensions(); d++) {
            sb.append("[0]");
        }
        return sb.toString();
    }
    if (Types.STRING_REF.equals(typeRef) && value != null && !String.valueOf(value).startsWith("\"")) {
        return "\"" + value + "\"";
    } else if (value instanceof Element) {
        Element element = (Element) value;
        if (element.getKind() == ElementKind.ENUM_CONSTANT) {
            return element.getEnclosingElement() + "." + element.getSimpleName();
        }
    } else if (stringVal != null && stringVal.startsWith("@")) {
        String annotationFQCN = stringVal.substring(1);
        TypeDef annotationDef = DefinitionRepository.getRepository().getDefinition(annotationFQCN);
        if (annotationDef != null) {
            TypeDef pojoDef = ClazzAs.POJO.apply(TypeArguments.apply(annotationDef));
            Optional<AnnotationRef> pojoAnnotation = getPojoAnnotation(pojoDef);
            Optional<Method> builderFromDefaults = getBuilderFromDefaults(pojoDef);
            if (pojoAnnotation.isPresent() && builderFromDefaults.isPresent()) {
                return pojoDef.getFullyQualifiedName() + "." + builderFromDefaults.get().getName() + "().build()";
            } else if (BuilderUtils.hasDefaultConstructor(pojoDef)) {
                return "new " + pojoDef.getFullyQualifiedName() + "()";
            }
        }
        return "null";
    } else if (stringVal == null && typeRef instanceof PrimitiveRef) {
        if (((PrimitiveRef) typeRef).getName().equals("boolean")) {
            return "false";
        } else {
            return "0";
        }
    }
    return stringVal;
}
Also used : ClassRef(io.sundr.model.ClassRef) TypeRef(io.sundr.model.TypeRef) Element(javax.lang.model.element.Element) Method(io.sundr.model.Method) PrimitiveRef(io.sundr.model.PrimitiveRef) RichTypeDef(io.sundr.model.RichTypeDef) TypeDef(io.sundr.model.TypeDef) Property(io.sundr.model.Property) AnnotationRef(io.sundr.model.AnnotationRef)

Example 17 with TypeRef

use of io.sundr.model.TypeRef 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 18 with TypeRef

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

the class Generify method findTypeArguments.

private static Set<TypeRef> findTypeArguments(Set<ClassRef> interfaces) {
    if (interfaces.size() < 2) {
        return Collections.<TypeRef>emptySet();
    }
    // 1st pass find all generics
    Set<TypeRef> allGenerics = new LinkedHashSet<TypeRef>();
    for (ClassRef clazz : interfaces) {
        allGenerics.addAll(clazz.getArguments());
    }
    // 2nd pass collect common generics
    Set<TypeRef> common = new LinkedHashSet<TypeRef>(allGenerics);
    for (ClassRef clazz : interfaces) {
        Set<TypeRef> ownGenerics = new LinkedHashSet<TypeRef>();
        ownGenerics.addAll(clazz.getArguments());
        common.remove(clazz);
        common.retainAll(ownGenerics);
    }
    Set<TypeRef> result = new LinkedHashSet<TypeRef>();
    for (TypeRef type : common) {
        Boolean isGeneric = type.getAttributes().containsKey(IS_GENERIC) ? (Boolean) type.getAttributes().get(IS_GENERIC) : false;
        if (!isGeneric) {
            result.add(type);
        }
    }
    return result;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) ClassRef(io.sundr.model.ClassRef) TypeRef(io.sundr.model.TypeRef)

Example 19 with TypeRef

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

the class TypeDefUtils method executableToInterface.

/**
 * Convert an {@link javax.lang.model.element.ExecutableElement} to a {@link io.sundr.model.TypeDef}
 *
 * @param context The context of the operation.
 * @param executableElement The target element.
 * @return An instance of {@link io.sundr.model.TypeDef} that describes the interface.
 */
public static TypeDef executableToInterface(DslContext context, ExecutableElement executableElement) {
    // Do generate the interface
    Boolean multiple = executableElement.getAnnotation(Multiple.class) != null;
    Boolean isEntryPoint = executableElement.getAnnotation(EntryPoint.class) != null;
    Boolean isTerminal = executableElement.getAnnotation(Terminal.class) != null || !isVoid(executableElement);
    Set<String> classes = new HashSet<String>();
    Set<String> keywords = new HashSet<String>();
    Set<String> methods = new HashSet<String>();
    TransitionFilter filter = executableElement.getAnnotation(Or.class) != null ? new OrTransitionFilter(context.getToRequiresAll().apply(executableElement), context.getToRequiresAny().apply(executableElement), context.getToRequiresOnly().apply(executableElement), context.getToRequiresNoneOf().apply(executableElement)) : new AndTransitionFilter(context.getToRequiresAll().apply(executableElement), context.getToRequiresAny().apply(executableElement), context.getToRequiresOnly().apply(executableElement), context.getToRequiresNoneOf().apply(executableElement));
    for (String clazz : context.getToClasses().apply(executableElement)) {
        classes.add(clazz);
    }
    for (String keyword : context.getToKeywords().apply(executableElement)) {
        keywords.add(keyword);
    }
    // Let's add the name of the method as a keyword to make things simpler
    methods.add(executableElement.getSimpleName().toString());
    TypeRef returnType;
    if (isTerminal(executableElement)) {
        returnType = isVoid(executableElement) ? VOID_REF : Adapters.adaptReference(executableElement.getReturnType(), context.getAptContext());
    } else {
        returnType = TRANSPARENT_REF;
    }
    InterfaceName targetInterfaceName = executableElement.getAnnotation(InterfaceName.class);
    MethodName tagetMethodName = executableElement.getAnnotation(MethodName.class);
    Begin begin = executableElement.getAnnotation(Begin.class);
    End end = executableElement.getAnnotation(End.class);
    if (begin != null) {
        keywords.add(begin.value());
    }
    if (end != null) {
        keywords.add(end.value());
    }
    String methodName = tagetMethodName != null ? tagetMethodName.value() : executableElement.getSimpleName().toString();
    String beginScope = begin != null ? begin.value() : null;
    String endScope = end != null ? end.value() : null;
    TypeParamDef paremeterType = Generics.MAP.apply(returnType);
    Method sourceMethod = Adapters.adaptMethod(executableElement, context.getAptContext());
    List<AnnotationRef> annotations = new ArrayList<AnnotationRef>();
    for (AnnotationRef candidate : sourceMethod.getAnnotations()) {
        if (!candidate.getClassRef().getFullyQualifiedName().startsWith("io.sundr")) {
            annotations.add(candidate);
        }
    }
    Method targetMethod = new MethodBuilder(sourceMethod).withAnnotations(annotations).withModifiers(Types.modifiersToInt(Modifier.PUBLIC)).withReturnType(paremeterType.toReference()).withName(methodName).build();
    String interfaceName = targetInterfaceName != null ? targetInterfaceName.value() : toInterfaceName(targetMethod.getName());
    return new TypeDefBuilder().withPackageName(Apt.getPackageElement(executableElement).toString()).withName(interfaceName).withParameters(paremeterType).withKind(Kind.INTERFACE).withModifiers(Types.modifiersToInt(Modifier.PUBLIC)).addToAttributes(ORIGINAL_RETURN_TYPE, returnType).addToAttributes(IS_ENTRYPOINT, isEntryPoint).addToAttributes(IS_TERMINAL, isTerminal).addToAttributes(IS_GENERIC, Boolean.FALSE).addToAttributes(CLASSES, classes).addToAttributes(KEYWORDS, keywords).addToAttributes(METHODS, methods).addToAttributes(BEGIN_SCOPE, beginScope).addToAttributes(END_SCOPE, endScope).addToAttributes(FILTER, filter).addToAttributes(CARDINALITY_MULTIPLE, multiple).addToAttributes(METHOD_NAME, methodName).addToMethods(targetMethod).build();
}
Also used : AndTransitionFilter(io.sundr.dsl.internal.element.functions.filter.AndTransitionFilter) TypeParamDef(io.sundr.model.TypeParamDef) Multiple(io.sundr.dsl.annotations.Multiple) TypeRef(io.sundr.model.TypeRef) ArrayList(java.util.ArrayList) EntryPoint(io.sundr.dsl.annotations.EntryPoint) Method(io.sundr.model.Method) TypeDefBuilder(io.sundr.model.TypeDefBuilder) MethodBuilder(io.sundr.model.MethodBuilder) OrTransitionFilter(io.sundr.dsl.internal.element.functions.filter.OrTransitionFilter) AndTransitionFilter(io.sundr.dsl.internal.element.functions.filter.AndTransitionFilter) TransitionFilter(io.sundr.dsl.internal.element.functions.filter.TransitionFilter) OrTransitionFilter(io.sundr.dsl.internal.element.functions.filter.OrTransitionFilter) Begin(io.sundr.dsl.annotations.Begin) InterfaceName(io.sundr.dsl.annotations.InterfaceName) End(io.sundr.dsl.annotations.End) MethodName(io.sundr.dsl.annotations.MethodName) AnnotationRef(io.sundr.model.AnnotationRef) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Example 20 with TypeRef

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

the class TypeToTypeRef method apply.

@Override
public TypeRef apply(Type type) {
    if (type instanceof VoidType) {
        return new VoidRef();
    } else if (type instanceof WildcardType) {
        return new WildcardRef();
    } else if (type instanceof ReferenceType) {
        ReferenceType referenceType = (ReferenceType) type;
        int dimensions = referenceType.getArrayCount();
        TypeRef typeRef = apply(referenceType.getType());
        if (dimensions == 0) {
            return typeRef;
        } else if (typeRef instanceof ClassRef) {
            return new ClassRefBuilder((ClassRef) typeRef).withDimensions(dimensions).build();
        } else if (typeRef instanceof PrimitiveRef) {
            return new PrimitiveRefBuilder((PrimitiveRef) typeRef).withDimensions(dimensions).build();
        } else if (typeRef instanceof TypeParamRef) {
            return new TypeParamRefBuilder((TypeParamRef) typeRef).withDimensions(dimensions).build();
        }
    } else if (type instanceof PrimitiveType) {
        PrimitiveType primitiveType = (PrimitiveType) type;
        return new PrimitiveRefBuilder().withName(primitiveType.getType().name()).build();
    } else if (type instanceof ClassOrInterfaceType) {
        return classOrInterfaceToTypeRef.apply((ClassOrInterfaceType) type);
    }
    throw new IllegalArgumentException("Can't handle type:[" + type + "].");
}
Also used : VoidType(com.github.javaparser.ast.type.VoidType) PrimitiveRefBuilder(io.sundr.model.PrimitiveRefBuilder) ClassRef(io.sundr.model.ClassRef) TypeRef(io.sundr.model.TypeRef) VoidRef(io.sundr.model.VoidRef) ClassRefBuilder(io.sundr.model.ClassRefBuilder) WildcardRef(io.sundr.model.WildcardRef) PrimitiveRef(io.sundr.model.PrimitiveRef) ClassOrInterfaceType(com.github.javaparser.ast.type.ClassOrInterfaceType) TypeParamRefBuilder(io.sundr.model.TypeParamRefBuilder) ReferenceType(com.github.javaparser.ast.type.ReferenceType) TypeParamRef(io.sundr.model.TypeParamRef) WildcardType(com.github.javaparser.ast.type.WildcardType) PrimitiveType(com.github.javaparser.ast.type.PrimitiveType)

Aggregations

TypeRef (io.sundr.model.TypeRef)45 ClassRef (io.sundr.model.ClassRef)33 TypeDef (io.sundr.model.TypeDef)23 ArrayList (java.util.ArrayList)16 ClassRefBuilder (io.sundr.model.ClassRefBuilder)14 Method (io.sundr.model.Method)13 RichTypeDef (io.sundr.model.RichTypeDef)13 TypeDefBuilder (io.sundr.model.TypeDefBuilder)12 Property (io.sundr.model.Property)10 MethodBuilder (io.sundr.model.MethodBuilder)9 PropertyBuilder (io.sundr.model.PropertyBuilder)9 TypeParamRef (io.sundr.model.TypeParamRef)9 TypedVisitor (io.sundr.builder.TypedVisitor)8 AnnotationRef (io.sundr.model.AnnotationRef)8 List (java.util.List)8 TypeParamDef (io.sundr.model.TypeParamDef)7 HashMap (java.util.HashMap)7 AttributeKey (io.sundr.model.AttributeKey)6 Map (java.util.Map)6 Collectors (java.util.stream.Collectors)6