Search in sources :

Example 1 with Method

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

the class ClassToTypeDef method apply.

@Override
public TypeDef apply(Class item) {
    if (Object.class.equals(item)) {
        return TypeDef.OBJECT;
    }
    Kind kind = classToKind.apply(item);
    List<ClassRef> extendsList = new ArrayList<>();
    List<ClassRef> implementsList = new ArrayList<>();
    List<Property> properties = new ArrayList<>();
    List<Method> methods = new ArrayList<>();
    List<Method> constructors = new ArrayList<>();
    List<TypeParamDef> parameters = new ArrayList<>();
    if (item.getSuperclass() != null) {
        extendsList.add((ClassRef) typeToTypeRef.apply(item.getGenericSuperclass()));
        references.add(item.getSuperclass());
    }
    for (Class interfaceClass : item.getInterfaces()) {
        references.add(interfaceClass);
    }
    for (Type interfaceClass : item.getGenericInterfaces()) {
        TypeRef ref = typeToTypeRef.apply(interfaceClass);
        if (ref instanceof ClassRef) {
            implementsList.add((ClassRef) ref);
        }
    }
    constructors.addAll(getConstructors(item, references));
    methods.addAll(getMethods(item, references));
    properties.addAll(getProperties(item, references));
    for (TypeVariable typeVariable : item.getTypeParameters()) {
        List<ClassRef> bounds = new ArrayList<>();
        for (Type boundType : typeVariable.getBounds()) {
            TypeRef typeRef = typeToTypeRef.apply(boundType);
            if (typeRef instanceof ClassRef) {
                bounds.add((ClassRef) typeRef);
            }
        }
        parameters.add(new TypeParamDefBuilder().withName(typeVariable.getName()).withBounds(bounds).build());
    }
    String outerFQCN = item.getDeclaringClass() != null ? item.getDeclaringClass().getName() : null;
    TypeDef result = context.getDefinitionRepository().register(new TypeDefBuilder().withKind(kind).withOuterTypeName(outerFQCN).withName(item.getSimpleName()).withPackageName(item.getPackage() != null ? item.getPackage().getName() : null).withModifiers(item.getModifiers()).withParameters(parameters).withConstructors(constructors).withMethods(methods).withProperties(properties).withExtendsList(extendsList).withImplementsList(implementsList).build());
    Set<Class> copy = new HashSet<>(references);
    copy.stream().peek(c -> references.remove(c)).filter(c -> !c.equals(item)).filter(c -> !c.getName().startsWith("sun.") && !c.getName().toString().startsWith("com.sun.")).forEach(c -> {
        String referenceFQCN = c.getName().replaceAll(Pattern.quote("$"), ".");
        context.getDefinitionRepository().registerIfAbsent(referenceFQCN, () -> apply(c));
    });
    return result;
}
Also used : 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) TypeParamDef(io.sundr.model.TypeParamDef) ClassRef(io.sundr.model.ClassRef) TypeRef(io.sundr.model.TypeRef) ArrayList(java.util.ArrayList) Method(io.sundr.model.Method) TypeDefBuilder(io.sundr.model.TypeDefBuilder) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) TypeDef(io.sundr.model.TypeDef) TypeVariable(java.lang.reflect.TypeVariable) Kind(io.sundr.model.Kind) TypeParamDefBuilder(io.sundr.model.TypeParamDefBuilder) Property(io.sundr.model.Property) HashSet(java.util.HashSet)

Example 2 with Method

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

the class SundrioGenerator method createModel.

public TypeDef createModel(String name, Model model, AbstractJavaCodegen config, Map<String, Model> allDefinitions) {
    String prefix = name.contains(DOT) ? name.substring(0, name.lastIndexOf(DOT)) : EMPTY;
    String packageName = prefix.isEmpty() ? config.modelPackage() : config.modelPackage() + DOT + prefix;
    String className = prefix.isEmpty() ? name : name.substring(name.lastIndexOf(DOT) + 1);
    ClassRef superClass = null;
    List<ClassRef> interfaces = new ArrayList<>();
    List<Property> fields = new ArrayList<>();
    List<Method> methods = new ArrayList<>();
    if (model instanceof ComposedModel) {
        ComposedModel composed = (ComposedModel) model;
        // interfaces (intermediate models)
        if (composed.getInterfaces() != null) {
            for (RefModel _interface : composed.getInterfaces()) {
                Model interfaceModel = null;
                if (allDefinitions != null) {
                    interfaceModel = allDefinitions.get(_interface.getSimpleRef());
                }
            }
            return new TypeDefBuilder().withKind(Kind.CLASS).withPackageName(packageName).withName(className).withImplementsList(interfaces).withExtendsList(superClass).withProperties(fields).withMethods(methods).build();
        }
    }
    return null;
}
Also used : RefModel(io.swagger.models.RefModel) ClassRef(io.sundr.model.ClassRef) ComposedModel(io.swagger.models.ComposedModel) ArrayList(java.util.ArrayList) RefModel(io.swagger.models.RefModel) ComposedModel(io.swagger.models.ComposedModel) Model(io.swagger.models.Model) Method(io.sundr.model.Method) Property(io.sundr.model.Property) TypeDefBuilder(io.sundr.model.TypeDefBuilder)

Example 3 with Method

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

the class MethodDirective method render.

@Override
public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException {
    String block = "";
    Method method = null;
    Boolean isInterface = false;
    int level = 1;
    for (int i = 0; i < node.jjtGetNumChildren(); i++) {
        if (node.jjtGetChild(i) != null) {
            if (!(node.jjtGetChild(i) instanceof ASTBlock)) {
                // reading and casting inline parameters
                if (i == 0) {
                    method = (Method) node.jjtGetChild(i).value(context);
                } else if (i == 1) {
                    isInterface = (Boolean) node.jjtGetChild(i).value(context);
                } else if (i == 2) {
                    level = (Integer) node.jjtGetChild(i).value(context);
                } else {
                    break;
                }
            } else {
                // reading block content and rendering it
                StringWriter blockContent = new StringWriter();
                node.jjtGetChild(i).render(context, blockContent);
                block = blockContent.toString();
                break;
            }
        }
    }
    boolean hasBody = !method.isAbstract() && (!isInterface || method.isDefaultMethod());
    writeMethod(writer, method, block, hasBody, level);
    return true;
}
Also used : StringWriter(java.io.StringWriter) ASTBlock(org.apache.velocity.runtime.parser.node.ASTBlock) Method(io.sundr.model.Method)

Example 4 with Method

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

the class BuilderUtils method getInlineableConstructors.

public static Set<Method> getInlineableConstructors(Property property) {
    Set<Method> result = new HashSet<Method>();
    TypeRef typeRef = property.getTypeRef();
    TypeRef unwrapped = TypeAs.combine(TypeAs.UNWRAP_COLLECTION_OF, TypeAs.UNWRAP_ARRAY_OF, TypeAs.UNWRAP_OPTIONAL_OF).apply(typeRef);
    if (unwrapped instanceof ClassRef) {
        ClassRef classRef = (ClassRef) unwrapped;
        // We need to handle `new String(String str)` as a special case of Inlineable constructor and deprecate Inlineables of it before we acutally remove it, so here goes...
        if (STRING_REF.equals(typeRef)) {
            result.add(new MethodBuilder().withName("String").addNewArgument().withName("s").withTypeRef(classRef).endArgument().build());
            return result;
        }
        // We only want to inline non java types
        String pkg = Nameable.getPackageName(((ClassRef) unwrapped).getFullyQualifiedName());
        if (!Stream.of(NON_INLINABLE_PACKAGES).filter(s -> pkg.startsWith(s)).findAny().isPresent()) {
            for (Method candidate : GetDefinition.of((ClassRef) unwrapped).getConstructors()) {
                if (isInlineable(candidate)) {
                    result.add(candidate);
                }
            }
        }
    }
    return result;
}
Also used : INIT(io.sundr.model.Attributeable.INIT) Arrays(java.util.Arrays) TypeParamDefBuilder(io.sundr.model.TypeParamDefBuilder) Descendants(io.sundr.builder.internal.functions.Descendants) Optionals(io.sundr.model.utils.Optionals) TypeElement(javax.lang.model.element.TypeElement) Attributeable(io.sundr.model.Attributeable) Nameable(io.sundr.model.Nameable) ClassRef(io.sundr.model.ClassRef) Getter(io.sundr.model.utils.Getter) STRING_REF(io.sundr.model.utils.Types.STRING_REF) Map(java.util.Map) MirroredTypeException(javax.lang.model.type.MirroredTypeException) BuildableRepository(io.sundr.builder.internal.BuildableRepository) Path(java.nio.file.Path) Collections(io.sundr.model.utils.Collections) BuilderContext(io.sundr.builder.internal.BuilderContext) DefinitionRepository(io.sundr.model.repo.DefinitionRepository) Collection(java.util.Collection) Set(java.util.Set) Element(javax.lang.model.element.Element) Method(io.sundr.model.Method) Construct(io.sundr.builder.internal.functions.Construct) Collectors(java.util.stream.Collectors) io.sundr.builder.annotations(io.sundr.builder.annotations) ALSO_IMPORT(io.sundr.model.Attributeable.ALSO_IMPORT) List(java.util.List) ClassRefBuilder(io.sundr.model.ClassRefBuilder) Stream(java.util.stream.Stream) MethodBuilder(io.sundr.model.MethodBuilder) BuilderContextManager(io.sundr.builder.internal.BuilderContextManager) TypeParamDef(io.sundr.model.TypeParamDef) Strings.capitalizeFirst(io.sundr.utils.Strings.capitalizeFirst) StringStatement(io.sundr.model.StringStatement) TypeParamRef(io.sundr.model.TypeParamRef) GetDefinition(io.sundr.model.functions.GetDefinition) TypeDefBuilder(io.sundr.model.TypeDefBuilder) AdapterContext(io.sundr.adapter.api.AdapterContext) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) INIT_FUNCTION(io.sundr.model.Attributeable.INIT_FUNCTION) Assignable(io.sundr.model.functions.Assignable) Types(io.sundr.model.utils.Types) LinkedHashSet(java.util.LinkedHashSet) Constants(io.sundr.builder.Constants) AptContext(io.sundr.adapter.apt.AptContext) TypedVisitor(io.sundr.builder.TypedVisitor) Adapters(io.sundr.adapter.api.Adapters) LAZY_INIT(io.sundr.model.Attributeable.LAZY_INIT) TypeRef(io.sundr.model.TypeRef) Types.isAbstract(io.sundr.model.utils.Types.isAbstract) AnnotationRef(io.sundr.model.AnnotationRef) Kind(io.sundr.model.Kind) Property(io.sundr.model.Property) File(java.io.File) LAZY_COLLECTIONS_INIT_ENABLED(io.sundr.builder.Constants.LAZY_COLLECTIONS_INIT_ENABLED) Statement(io.sundr.model.Statement) TypeDef(io.sundr.model.TypeDef) DEFAULT_VALUE(io.sundr.model.Attributeable.DEFAULT_VALUE) PropertyBuilder(io.sundr.model.PropertyBuilder) TypeAs(io.sundr.builder.internal.functions.TypeAs) DESCENDANTS(io.sundr.builder.Constants.DESCENDANTS) ClassRef(io.sundr.model.ClassRef) TypeRef(io.sundr.model.TypeRef) Method(io.sundr.model.Method) MethodBuilder(io.sundr.model.MethodBuilder) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Example 5 with Method

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

the class ToPojo method readObjectArrayValue.

/**
 * Returns the string representation of the code that reads an object array property.
 *
 * @param ref The reference.
 * @param source The type of the reference.
 * @param property The property to read.
 * @return The code.
 */
private static String readObjectArrayValue(String ref, TypeDef source, Property property) {
    StringBuilder sb = new StringBuilder();
    Method getter = getterOf(source, property);
    TypeRef getterTypeRef = getter.getReturnType();
    TypeRef propertyTypeRef = property.getTypeRef();
    if (propertyTypeRef instanceof ClassRef && getterTypeRef instanceof ClassRef) {
        String nextRef = variables.pop();
        try {
            TypeDef propertyType = GetDefinition.of((ClassRef) propertyTypeRef);
            TypeDef getterType = GetDefinition.of((ClassRef) getterTypeRef);
            if (Types.STRING.equals(getterType)) {
                sb.append(ref + " instanceof Map ? toStringArray(((Map)" + ref + ").get(\"" + getter.getName() + "\")) : toStringArray(" + ref + ")");
            } else {
                sb.append(indent(ref)).append("Arrays.stream(");
                sb.append("(Map[])(" + ref + " instanceof Map ? ((Map)" + ref + ").getOrDefault(\"" + getter.getName() + "\" , new Map[0]) : new Map[0]))");
                sb.append(".map(").append(nextRef).append(" ->").append(convertMap(nextRef, getterType, propertyType)).append(")");
                sb.append(".toArray(size-> new " + propertyType.getFullyQualifiedName() + "[size])");
            }
        } finally {
            variables.push(nextRef);
        }
        return sb.toString();
    }
    throw new IllegalArgumentException("Expected an object property and a matching object getter!!");
}
Also used : ClassRef(io.sundr.model.ClassRef) RichTypeDef(io.sundr.model.RichTypeDef) TypeDef(io.sundr.model.TypeDef) TypeRef(io.sundr.model.TypeRef) Method(io.sundr.model.Method)

Aggregations

Method (io.sundr.model.Method)30 TypeDef (io.sundr.model.TypeDef)21 ClassRef (io.sundr.model.ClassRef)20 Property (io.sundr.model.Property)18 TypeRef (io.sundr.model.TypeRef)17 ArrayList (java.util.ArrayList)17 AnnotationRef (io.sundr.model.AnnotationRef)14 TypeDefBuilder (io.sundr.model.TypeDefBuilder)14 MethodBuilder (io.sundr.model.MethodBuilder)13 RichTypeDef (io.sundr.model.RichTypeDef)13 TypeParamDef (io.sundr.model.TypeParamDef)9 HashSet (java.util.HashSet)9 List (java.util.List)9 PropertyBuilder (io.sundr.model.PropertyBuilder)8 Set (java.util.Set)8 Collectors (java.util.stream.Collectors)8 AttributeKey (io.sundr.model.AttributeKey)7 Statement (io.sundr.model.Statement)7 StringStatement (io.sundr.model.StringStatement)7 Types (io.sundr.model.utils.Types)7