Search in sources :

Example 1 with FieldDefinition

use of com.palantir.conjure.spec.FieldDefinition in project conjure-java by palantir.

the class UnionGenerator method generateBase.

private static TypeSpec generateBase(ClassName baseClass, ClassName visitorClass, Map<FieldDefinition, TypeName> memberTypes) {
    ClassName unknownWrapperClass = baseClass.peerClass(UNKNOWN_WRAPPER_CLASS_NAME);
    TypeSpec.Builder baseBuilder = TypeSpec.interfaceBuilder(baseClass).addModifiers(Modifier.PRIVATE).addAnnotation(AnnotationSpec.builder(JsonTypeInfo.class).addMember("use", "JsonTypeInfo.Id.NAME").addMember("include", "JsonTypeInfo.As.EXISTING_PROPERTY").addMember("property", "\"type\"").addMember("visible", "$L", true).addMember("defaultImpl", "$T.class", unknownWrapperClass).build());
    if (!memberTypes.isEmpty()) {
        List<AnnotationSpec> subAnnotations = memberTypes.entrySet().stream().map(entry -> AnnotationSpec.builder(JsonSubTypes.Type.class).addMember("value", "$T.class", peerWrapperClass(baseClass, sanitizeUnknown(entry.getKey().getFieldName()))).build()).collect(Collectors.toList());
        AnnotationSpec.Builder annotationBuilder = AnnotationSpec.builder(JsonSubTypes.class);
        subAnnotations.forEach(subAnnotation -> annotationBuilder.addMember("value", "$L", subAnnotation));
        baseBuilder.addAnnotation(annotationBuilder.build());
    }
    baseBuilder.addAnnotation(AnnotationSpec.builder(JsonIgnoreProperties.class).addMember("ignoreUnknown", "$L", true).build());
    ParameterizedTypeName parameterizedVisitorClass = ParameterizedTypeName.get(visitorClass, TYPE_VARIABLE);
    ParameterSpec visitor = ParameterSpec.builder(parameterizedVisitorClass, "visitor").build();
    baseBuilder.addMethod(MethodSpec.methodBuilder("accept").addTypeVariable(TYPE_VARIABLE).addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT).addParameter(visitor).returns(TYPE_VARIABLE).build());
    return baseBuilder.build();
}
Also used : JsonProperty(com.fasterxml.jackson.annotation.JsonProperty) Modifier(javax.lang.model.element.Modifier) Javadoc(com.palantir.conjure.java.util.Javadoc) DefaultableTypeVisitor(com.palantir.conjure.java.visitor.DefaultableTypeVisitor) BiFunction(java.util.function.BiFunction) ClassName(com.squareup.javapoet.ClassName) PeekingIterator(com.google.common.collect.PeekingIterator) StringUtils(org.apache.commons.lang3.StringUtils) Options(com.palantir.conjure.java.Options) JsonValue(com.fasterxml.jackson.annotation.JsonValue) Map(java.util.Map) JsonAnyGetter(com.fasterxml.jackson.annotation.JsonAnyGetter) StableCollectors(com.palantir.conjure.java.util.StableCollectors) ParameterSpec(com.squareup.javapoet.ParameterSpec) SafeIllegalArgumentException(com.palantir.logsafe.exceptions.SafeIllegalArgumentException) FieldDefinition(com.palantir.conjure.spec.FieldDefinition) Collectors(java.util.stream.Collectors) JavaFile(com.squareup.javapoet.JavaFile) JsonAnySetter(com.fasterxml.jackson.annotation.JsonAnySetter) List(java.util.List) Stream(java.util.stream.Stream) JsonTypeInfo(com.fasterxml.jackson.annotation.JsonTypeInfo) TypeName(com.squareup.javapoet.TypeName) JsonIgnoreProperties(com.fasterxml.jackson.annotation.JsonIgnoreProperties) Nulls(com.fasterxml.jackson.annotation.Nulls) TypeFunctions(com.palantir.conjure.java.util.TypeFunctions) FieldSpec(com.squareup.javapoet.FieldSpec) Type(com.palantir.conjure.spec.Type) DoubleFunction(java.util.function.DoubleFunction) HashMap(java.util.HashMap) Function(java.util.function.Function) Iterators(com.google.common.collect.Iterators) ArrayList(java.util.ArrayList) UnionDefinition(com.palantir.conjure.spec.UnionDefinition) JsonTypeName(com.fasterxml.jackson.annotation.JsonTypeName) SafeArg(com.palantir.logsafe.SafeArg) ImmutableList(com.google.common.collect.ImmutableList) Nonnull(javax.annotation.Nonnull) CodeBlock(com.squareup.javapoet.CodeBlock) IntFunction(java.util.function.IntFunction) TypeVariableName(com.squareup.javapoet.TypeVariableName) TypeDefinition(com.palantir.conjure.spec.TypeDefinition) JsonSubTypes(com.fasterxml.jackson.annotation.JsonSubTypes) MethodSpec(com.squareup.javapoet.MethodSpec) Packages(com.palantir.conjure.java.util.Packages) JavaNameSanitizer(com.palantir.conjure.java.util.JavaNameSanitizer) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) TypeSpec(com.squareup.javapoet.TypeSpec) AnnotationSpec(com.squareup.javapoet.AnnotationSpec) ConjureAnnotations(com.palantir.conjure.java.ConjureAnnotations) FieldName(com.palantir.conjure.spec.FieldName) Comparator(java.util.Comparator) Collections(java.util.Collections) JsonSetter(com.fasterxml.jackson.annotation.JsonSetter) JsonSubTypes(com.fasterxml.jackson.annotation.JsonSubTypes) ParameterSpec(com.squareup.javapoet.ParameterSpec) ClassName(com.squareup.javapoet.ClassName) JsonTypeInfo(com.fasterxml.jackson.annotation.JsonTypeInfo) AnnotationSpec(com.squareup.javapoet.AnnotationSpec) TypeSpec(com.squareup.javapoet.TypeSpec) JsonIgnoreProperties(com.fasterxml.jackson.annotation.JsonIgnoreProperties) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName)

Example 2 with FieldDefinition

use of com.palantir.conjure.spec.FieldDefinition in project conjure-java by palantir.

the class UnionGenerator method generateUnionType.

public static JavaFile generateUnionType(TypeMapper typeMapper, Map<com.palantir.conjure.spec.TypeName, TypeDefinition> typesMap, UnionDefinition typeDef, Options options) {
    com.palantir.conjure.spec.TypeName prefixedTypeName = Packages.getPrefixedName(typeDef.getTypeName(), options.packagePrefix());
    ClassName unionClass = ClassName.get(prefixedTypeName.getPackage(), prefixedTypeName.getName());
    ClassName baseClass = unionClass.nestedClass("Base");
    ClassName visitorClass = unionClass.nestedClass("Visitor");
    ClassName visitorBuilderClass = unionClass.nestedClass("VisitorBuilder");
    Map<FieldDefinition, TypeName> memberTypes = typeDef.getUnion().stream().collect(StableCollectors.toLinkedMap(Function.identity(), entry -> typeMapper.getClassName(entry.getType())));
    List<FieldSpec> fields = ImmutableList.of(FieldSpec.builder(baseClass, VALUE_FIELD_NAME, Modifier.PRIVATE, Modifier.FINAL).build());
    TypeSpec.Builder typeBuilder = TypeSpec.classBuilder(typeDef.getTypeName().getName()).addAnnotation(ConjureAnnotations.getConjureGeneratedAnnotation(UnionGenerator.class)).addModifiers(Modifier.PUBLIC, Modifier.FINAL).addFields(fields).addMethod(generateConstructor(baseClass)).addMethod(generateGetValue(baseClass)).addMethods(generateStaticFactories(typeMapper, unionClass, typeDef.getUnion())).addMethod(generateAcceptVisitMethod(visitorClass)).addType(generateVisitor(unionClass, visitorClass, memberTypes, visitorBuilderClass, options)).addType(generateVisitorBuilder(unionClass, visitorClass, visitorBuilderClass, memberTypes, options)).addTypes(generateVisitorBuilderStageInterfaces(unionClass, visitorClass, memberTypes, options)).addType(generateBase(baseClass, visitorClass, memberTypes)).addTypes(generateWrapperClasses(typeMapper, typesMap, baseClass, visitorClass, typeDef.getUnion(), options)).addType(generateUnknownWrapper(baseClass, visitorClass, options)).addMethod(generateEquals(unionClass)).addMethod(MethodSpecs.createEqualTo(unionClass, fields)).addMethod(MethodSpecs.createHashCode(fields)).addMethod(MethodSpecs.createToString(unionClass.simpleName(), fields.stream().map(fieldSpec -> FieldName.of(fieldSpec.name)).collect(Collectors.toList())));
    typeDef.getDocs().ifPresent(docs -> typeBuilder.addJavadoc("$L", Javadoc.render(docs)));
    return JavaFile.builder(prefixedTypeName.getPackage(), typeBuilder.build()).skipJavaLangImports(true).indent("    ").build();
}
Also used : JsonProperty(com.fasterxml.jackson.annotation.JsonProperty) Modifier(javax.lang.model.element.Modifier) Javadoc(com.palantir.conjure.java.util.Javadoc) DefaultableTypeVisitor(com.palantir.conjure.java.visitor.DefaultableTypeVisitor) BiFunction(java.util.function.BiFunction) ClassName(com.squareup.javapoet.ClassName) PeekingIterator(com.google.common.collect.PeekingIterator) StringUtils(org.apache.commons.lang3.StringUtils) Options(com.palantir.conjure.java.Options) JsonValue(com.fasterxml.jackson.annotation.JsonValue) Map(java.util.Map) JsonAnyGetter(com.fasterxml.jackson.annotation.JsonAnyGetter) StableCollectors(com.palantir.conjure.java.util.StableCollectors) ParameterSpec(com.squareup.javapoet.ParameterSpec) SafeIllegalArgumentException(com.palantir.logsafe.exceptions.SafeIllegalArgumentException) FieldDefinition(com.palantir.conjure.spec.FieldDefinition) Collectors(java.util.stream.Collectors) JavaFile(com.squareup.javapoet.JavaFile) JsonAnySetter(com.fasterxml.jackson.annotation.JsonAnySetter) List(java.util.List) Stream(java.util.stream.Stream) JsonTypeInfo(com.fasterxml.jackson.annotation.JsonTypeInfo) TypeName(com.squareup.javapoet.TypeName) JsonIgnoreProperties(com.fasterxml.jackson.annotation.JsonIgnoreProperties) Nulls(com.fasterxml.jackson.annotation.Nulls) TypeFunctions(com.palantir.conjure.java.util.TypeFunctions) FieldSpec(com.squareup.javapoet.FieldSpec) Type(com.palantir.conjure.spec.Type) DoubleFunction(java.util.function.DoubleFunction) HashMap(java.util.HashMap) Function(java.util.function.Function) Iterators(com.google.common.collect.Iterators) ArrayList(java.util.ArrayList) UnionDefinition(com.palantir.conjure.spec.UnionDefinition) JsonTypeName(com.fasterxml.jackson.annotation.JsonTypeName) SafeArg(com.palantir.logsafe.SafeArg) ImmutableList(com.google.common.collect.ImmutableList) Nonnull(javax.annotation.Nonnull) CodeBlock(com.squareup.javapoet.CodeBlock) IntFunction(java.util.function.IntFunction) TypeVariableName(com.squareup.javapoet.TypeVariableName) TypeDefinition(com.palantir.conjure.spec.TypeDefinition) JsonSubTypes(com.fasterxml.jackson.annotation.JsonSubTypes) MethodSpec(com.squareup.javapoet.MethodSpec) Packages(com.palantir.conjure.java.util.Packages) JavaNameSanitizer(com.palantir.conjure.java.util.JavaNameSanitizer) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) TypeSpec(com.squareup.javapoet.TypeSpec) AnnotationSpec(com.squareup.javapoet.AnnotationSpec) ConjureAnnotations(com.palantir.conjure.java.ConjureAnnotations) FieldName(com.palantir.conjure.spec.FieldName) Comparator(java.util.Comparator) Collections(java.util.Collections) JsonSetter(com.fasterxml.jackson.annotation.JsonSetter) TypeName(com.squareup.javapoet.TypeName) JsonTypeName(com.fasterxml.jackson.annotation.JsonTypeName) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) FieldDefinition(com.palantir.conjure.spec.FieldDefinition) FieldSpec(com.squareup.javapoet.FieldSpec) ClassName(com.squareup.javapoet.ClassName) TypeSpec(com.squareup.javapoet.TypeSpec)

Example 3 with FieldDefinition

use of com.palantir.conjure.spec.FieldDefinition in project conjure by palantir.

the class ObjectDefinitionValidatorTest method testUniqueFieldNameValidator.

private void testUniqueFieldNameValidator(String fieldName1, String fieldName2) {
    FieldDefinition field1 = FieldDefinition.builder().fieldName(FieldName.of(fieldName1)).type(Type.primitive(PrimitiveType.STRING)).build();
    FieldDefinition field2 = FieldDefinition.builder().fieldName(FieldName.of(fieldName2)).type(Type.primitive(PrimitiveType.STRING)).build();
    TypeName name = TypeName.of("Foo", "package");
    ObjectDefinition definition = ObjectDefinition.builder().typeName(name).fields(field1).fields(field2).build();
    assertThatThrownBy(() -> ObjectDefinitionValidator.validate(definition)).isInstanceOf(IllegalArgumentException.class).hasMessage(String.format("ObjectDefinition must not contain duplicate field names " + "(modulo case normalization): %s vs %s", fieldName2, fieldName1));
}
Also used : TypeName(com.palantir.conjure.spec.TypeName) FieldDefinition(com.palantir.conjure.spec.FieldDefinition) ObjectDefinition(com.palantir.conjure.spec.ObjectDefinition)

Example 4 with FieldDefinition

use of com.palantir.conjure.spec.FieldDefinition in project conjure by palantir.

the class FieldDefinitionValidatorTest method assertInvalidType.

private void assertInvalidType(Type type) {
    String illegalFieldName = "asdf";
    FieldDefinition fieldDefinition = FieldDefinition.builder().fieldName(FieldName.of(illegalFieldName)).type(type).docs(Documentation.of("docs")).build();
    assertThatThrownBy(() -> FieldDefinitionValidator.validate(fieldDefinition)).isInstanceOf(IllegalStateException.class).hasMessageContaining(illegalFieldName).hasMessageContaining(COMPLEX_KEY_TYPE.toString());
}
Also used : FieldDefinition(com.palantir.conjure.spec.FieldDefinition)

Example 5 with FieldDefinition

use of com.palantir.conjure.spec.FieldDefinition in project conjure-postman by palantir.

the class TemplateTypeVisitor method visitReference.

@SuppressWarnings("PreferSafeLoggingPreconditions")
@Override
public JsonNode visitReference(TypeName value) {
    TypeDefinition definition = types.get(value);
    TemplateTypeVisitor visitor = this;
    return definition.accept(new TypeDefinition.Visitor<JsonNode>() {

        @Override
        public JsonNode visitAlias(AliasDefinition value) {
            JsonNode wrapped = value.getAlias().accept(visitor);
            if (wrapped instanceof TextNode) {
                return new TextNode(String.format("{{ %s(%s) }}", value.getTypeName().getName(), wrapped.toString().replaceAll("[\"{}]", "")));
            }
            return wrapped;
        }

        @Override
        public JsonNode visitEnum(EnumDefinition value) {
            return new TextNode(value.getValues().stream().map(EnumValueDefinition::getValue).collect(Collectors.joining("|")));
        }

        @Override
        public JsonNode visitObject(ObjectDefinition value) {
            if (seenTypeStack.contains(value.getTypeName())) {
                return new TextNode(String.format("{{%s}}", value.getTypeName().getName()));
            }
            seenTypeStack.push(value.getTypeName());
            ObjectNode node = objectMapper.createObjectNode();
            value.getFields().forEach(fieldDefinition -> node.set(fieldDefinition.getFieldName().get(), fieldDefinition.getType().accept(visitor)));
            Preconditions.checkState(seenTypeStack.pop().equals(value.getTypeName()));
            return node;
        }

        @Override
        public JsonNode visitUnion(UnionDefinition value) {
            if (value.getUnion().isEmpty()) {
                return null;
            } else {
                if (seenTypeStack.contains(value.getTypeName())) {
                    return new TextNode(String.format("{{%s}}", value.getTypeName().getName()));
                }
                seenTypeStack.push(value.getTypeName());
                String unionTypes = value.getUnion().stream().map(FieldDefinition::getFieldName).map(FieldName::get).collect(Collectors.joining("|"));
                ObjectNode templates = objectMapper.createObjectNode();
                value.getUnion().forEach(field -> templates.set(field.getFieldName().get(), field.getType().accept(visitor)));
                JsonNode union = objectMapper.createObjectNode().put("type", unionTypes).set("oneOf", templates);
                Preconditions.checkState(seenTypeStack.pop().equals(value.getTypeName()));
                return union;
            }
        }

        @Override
        public JsonNode visitUnknown(String _unknownType) {
            return new TextNode("{{UNKNOWN}}");
        }
    });
}
Also used : ListType(com.palantir.conjure.spec.ListType) ExternalReference(com.palantir.conjure.spec.ExternalReference) Type(com.palantir.conjure.spec.Type) TypeDefinitionVisitor(com.palantir.conjure.visitor.TypeDefinitionVisitor) Function(java.util.function.Function) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) UnionDefinition(com.palantir.conjure.spec.UnionDefinition) MapType(com.palantir.conjure.spec.MapType) Map(java.util.Map) OptionalType(com.palantir.conjure.spec.OptionalType) JsonNode(com.fasterxml.jackson.databind.JsonNode) SetType(com.palantir.conjure.spec.SetType) TypeDefinition(com.palantir.conjure.spec.TypeDefinition) ObjectDefinition(com.palantir.conjure.spec.ObjectDefinition) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) EnumDefinition(com.palantir.conjure.spec.EnumDefinition) EnumValueDefinition(com.palantir.conjure.spec.EnumValueDefinition) FieldDefinition(com.palantir.conjure.spec.FieldDefinition) Collectors(java.util.stream.Collectors) TextNode(com.fasterxml.jackson.databind.node.TextNode) Jdk8Module(com.fasterxml.jackson.datatype.jdk8.Jdk8Module) List(java.util.List) AliasDefinition(com.palantir.conjure.spec.AliasDefinition) TypeName(com.palantir.conjure.spec.TypeName) SerializationFeature(com.fasterxml.jackson.databind.SerializationFeature) Preconditions(com.google.common.base.Preconditions) FieldName(com.palantir.conjure.spec.FieldName) PrimitiveType(com.palantir.conjure.spec.PrimitiveType) ArrayDeque(java.util.ArrayDeque) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) AliasDefinition(com.palantir.conjure.spec.AliasDefinition) UnionDefinition(com.palantir.conjure.spec.UnionDefinition) JsonNode(com.fasterxml.jackson.databind.JsonNode) TextNode(com.fasterxml.jackson.databind.node.TextNode) ObjectDefinition(com.palantir.conjure.spec.ObjectDefinition) EnumDefinition(com.palantir.conjure.spec.EnumDefinition) TypeDefinition(com.palantir.conjure.spec.TypeDefinition) FieldName(com.palantir.conjure.spec.FieldName)

Aggregations

FieldDefinition (com.palantir.conjure.spec.FieldDefinition)14 Type (com.palantir.conjure.spec.Type)8 FieldName (com.palantir.conjure.spec.FieldName)5 MapType (com.palantir.conjure.spec.MapType)5 PrimitiveType (com.palantir.conjure.spec.PrimitiveType)5 TypeDefinition (com.palantir.conjure.spec.TypeDefinition)5 FieldSpec (com.squareup.javapoet.FieldSpec)5 List (java.util.List)5 Map (java.util.Map)5 Collectors (java.util.stream.Collectors)5 Test (org.junit.jupiter.api.Test)5 JsonIgnoreProperties (com.fasterxml.jackson.annotation.JsonIgnoreProperties)4 ImmutableList (com.google.common.collect.ImmutableList)4 ConjureAnnotations (com.palantir.conjure.java.ConjureAnnotations)4 Options (com.palantir.conjure.java.Options)4 JavaNameSanitizer (com.palantir.conjure.java.util.JavaNameSanitizer)4 TypeFunctions (com.palantir.conjure.java.util.TypeFunctions)4 ListType (com.palantir.conjure.spec.ListType)4 ObjectDefinition (com.palantir.conjure.spec.ObjectDefinition)4 OptionalType (com.palantir.conjure.spec.OptionalType)4