Search in sources :

Example 1 with AnnotationRef

use of io.sundr.model.AnnotationRef in project kubernetes-client by fabric8io.

the class AbstractCustomResourceHandler method handle.

public void handle(CustomResourceInfo config) {
    final String name = config.crdName();
    final String version = config.version();
    TypeDef def = config.definition();
    SpecReplicasPathDetector specReplicasPathDetector = new SpecReplicasPathDetector();
    StatusReplicasPathDetector statusReplicasPathDetector = new StatusReplicasPathDetector();
    LabelSelectorPathDetector labelSelectorPathDetector = new LabelSelectorPathDetector();
    AdditionalPrinterColumnDetector additionalPrinterColumnDetector = new AdditionalPrinterColumnDetector();
    ClassDependenciesVisitor traversedClassesVisitor = new ClassDependenciesVisitor(config.crClassName(), name);
    TypeDefBuilder builder = new TypeDefBuilder(def);
    if (config.specClassName().isPresent()) {
        builder.accept(specReplicasPathDetector);
    }
    if (config.statusClassName().isPresent()) {
        builder.accept(statusReplicasPathDetector);
    }
    def = builder.accept(labelSelectorPathDetector).accept(additionalPrinterColumnDetector).accept(traversedClassesVisitor).build();
    addDecorators(config, def, specReplicasPathDetector.getPath(), statusReplicasPathDetector.getPath(), labelSelectorPathDetector.getPath());
    Map<String, Property> additionalPrinterColumns = new HashMap<>(additionalPrinterColumnDetector.getProperties());
    additionalPrinterColumns.forEach((path, property) -> {
        Map<String, Object> parameters = property.getAnnotations().stream().filter(a -> a.getClassRef().getName().equals("PrinterColumn")).map(AnnotationRef::getParameters).findFirst().orElse(Collections.emptyMap());
        String type = AbstractJsonSchema.getSchemaTypeFor(property.getTypeRef());
        String column = (String) parameters.get("name");
        if (Utils.isNullOrEmpty(column)) {
            column = property.getName().toUpperCase();
        }
        String description = property.getComments().stream().filter(l -> !l.trim().startsWith("@")).collect(Collectors.joining(" ")).trim();
        String format = (String) parameters.get("format");
        resources.decorate(getPrinterColumnDecorator(name, version, path, type, column, description, format));
    });
}
Also used : Utils(io.fabric8.kubernetes.client.utils.Utils) Decorator(io.fabric8.crd.generator.decorator.Decorator) io.fabric8.crd.generator.visitor(io.fabric8.crd.generator.visitor) Map(java.util.Map) TypeDef(io.sundr.model.TypeDef) Optional(java.util.Optional) HashMap(java.util.HashMap) AnnotationRef(io.sundr.model.AnnotationRef) TypeDefBuilder(io.sundr.model.TypeDefBuilder) Property(io.sundr.model.Property) Collections(java.util.Collections) Collectors(java.util.stream.Collectors) HashMap(java.util.HashMap) TypeDefBuilder(io.sundr.model.TypeDefBuilder) TypeDef(io.sundr.model.TypeDef) Property(io.sundr.model.Property) AnnotationRef(io.sundr.model.AnnotationRef)

Example 2 with AnnotationRef

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

the class ClassToTypeDef method getProperties.

private Set<Property> getProperties(Class item, Set<Class> references) {
    Set<Property> properties = new HashSet<Property>();
    for (Field field : item.getDeclaredFields()) {
        List<AnnotationRef> annotationRefs = new ArrayList<AnnotationRef>();
        processAnnotatedElement(field, annotationRefs);
        if (field.getGenericType() instanceof Class) {
            references.add((Class) field.getGenericType());
        }
        // If property contains generic bounds, we need to process them too.
        if (field.getGenericType() instanceof ParameterizedType) {
            ParameterizedType p = (ParameterizedType) field.getGenericType();
            references.addAll(Stream.of(p.getActualTypeArguments()).filter(t -> t instanceof Class).map(t -> (Class) t).filter(c -> !item.equals(c)).collect(Collectors.toList()));
        }
        properties.add(new PropertyBuilder().withName(field.getName()).withModifiers(field.getModifiers()).withAnnotations(annotationRefs).withTypeRef(typeToTypeRef.apply(field.getGenericType())).build());
    }
    return properties;
}
Also used : ParameterizedType(java.lang.reflect.ParameterizedType) TypeParamDefBuilder(io.sundr.model.TypeParamDefBuilder) AnnotationRefBuilder(io.sundr.model.AnnotationRefBuilder) HashMap(java.util.HashMap) TypeDefBuilder(io.sundr.model.TypeDefBuilder) Function(java.util.function.Function) AdapterContext(io.sundr.adapter.api.AdapterContext) Attributeable(io.sundr.model.Attributeable) ArrayList(java.util.ArrayList) AttributeKey(io.sundr.model.AttributeKey) ClassRef(io.sundr.model.ClassRef) HashSet(java.util.HashSet) Map(java.util.Map) TypeVariable(java.lang.reflect.TypeVariable) Set(java.util.Set) Method(io.sundr.model.Method) TypeRef(io.sundr.model.TypeRef) Field(java.lang.reflect.Field) AnnotationRef(io.sundr.model.AnnotationRef) Kind(io.sundr.model.Kind) Collectors(java.util.stream.Collectors) Property(io.sundr.model.Property) InvocationTargetException(java.lang.reflect.InvocationTargetException) List(java.util.List) Stream(java.util.stream.Stream) MethodBuilder(io.sundr.model.MethodBuilder) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) Annotation(java.lang.annotation.Annotation) TypeDef(io.sundr.model.TypeDef) PropertyBuilder(io.sundr.model.PropertyBuilder) Pattern(java.util.regex.Pattern) TypeParamDef(io.sundr.model.TypeParamDef) AnnotatedElement(java.lang.reflect.AnnotatedElement) Field(java.lang.reflect.Field) ArrayList(java.util.ArrayList) Property(io.sundr.model.Property) AnnotationRef(io.sundr.model.AnnotationRef) HashSet(java.util.HashSet) PropertyBuilder(io.sundr.model.PropertyBuilder)

Example 3 with AnnotationRef

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

the class VariableElementToProperty method apply.

public Property apply(final VariableElement variableElement) {
    String name = variableElement.getSimpleName().toString();
    TypeRef type = referenceAdapterFunction.apply(variableElement.asType());
    List<AnnotationRef> annotations = new ArrayList<AnnotationRef>();
    for (AnnotationMirror annotationMirror : variableElement.getAnnotationMirrors()) {
        annotations.add(annotationAdapterFunction.apply(annotationMirror));
    }
    String comments = context.getElements().getDocComment(variableElement);
    List<String> commentList = Strings.isNullOrEmpty(comments) ? new ArrayList<>() : Arrays.stream(comments.split(NEWLINE_PATTERN)).map(String::trim).filter(s -> !s.isEmpty()).collect(Collectors.toList());
    return new PropertyBuilder().withComments(commentList).withName(name).withTypeRef(type).withAnnotations(annotations).withModifiers(Types.modifiersToInt(variableElement.getModifiers())).build();
}
Also used : AnnotationMirror(javax.lang.model.element.AnnotationMirror) TypeRef(io.sundr.model.TypeRef) ArrayList(java.util.ArrayList) AnnotationRef(io.sundr.model.AnnotationRef) PropertyBuilder(io.sundr.model.PropertyBuilder)

Example 4 with AnnotationRef

use of io.sundr.model.AnnotationRef 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 5 with AnnotationRef

use of io.sundr.model.AnnotationRef 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)

Aggregations

AnnotationRef (io.sundr.model.AnnotationRef)14 Method (io.sundr.model.Method)9 Property (io.sundr.model.Property)9 HashMap (java.util.HashMap)9 ClassRef (io.sundr.model.ClassRef)8 ArrayList (java.util.ArrayList)8 MethodBuilder (io.sundr.model.MethodBuilder)7 TypeRef (io.sundr.model.TypeRef)7 AttributeKey (io.sundr.model.AttributeKey)6 TypeDef (io.sundr.model.TypeDef)6 TypeDefBuilder (io.sundr.model.TypeDefBuilder)6 TypeParamDef (io.sundr.model.TypeParamDef)6 HashSet (java.util.HashSet)6 AnnotationRefBuilder (io.sundr.model.AnnotationRefBuilder)5 PropertyBuilder (io.sundr.model.PropertyBuilder)5 Annotation (java.lang.annotation.Annotation)5 InvocationTargetException (java.lang.reflect.InvocationTargetException)4 Map (java.util.Map)4 Collectors (java.util.stream.Collectors)4 Attributeable (io.sundr.model.Attributeable)3