Search in sources :

Example 1 with JacksonModule

use of com.github.victools.jsonschema.module.jackson.JacksonModule in project jsonschema-generator by victools.

the class SchemaGeneratorMojo method addJacksonModule.

/**
 * Add the Jackson module to the generator config.
 *
 * @param configBuilder The builder on which the config is added
 * @param module The modules section form the pom
 * @throws MojoExecutionException Exception in case of error
 */
private void addJacksonModule(SchemaGeneratorConfigBuilder configBuilder, GeneratorModule module) throws MojoExecutionException {
    if (module.options == null || module.options.length == 0) {
        configBuilder.with(new JacksonModule());
    } else {
        JacksonOption[] jacksonOptions = new JacksonOption[module.options.length];
        for (int i = 0; i < module.options.length; i++) {
            try {
                jacksonOptions[i] = JacksonOption.valueOf(module.options[i]);
            } catch (IllegalArgumentException e) {
                throw new MojoExecutionException("Error: Unknown Jackson option " + module.options[i], e);
            }
        }
        configBuilder.with(new JacksonModule(jacksonOptions));
    }
}
Also used : MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) JacksonOption(com.github.victools.jsonschema.module.jackson.JacksonOption) JacksonModule(com.github.victools.jsonschema.module.jackson.JacksonModule)

Example 2 with JacksonModule

use of com.github.victools.jsonschema.module.jackson.JacksonModule in project jreleaser by jreleaser.

the class JsonSchema method execute.

protected void execute() {
    Map<String, String> mappings = new LinkedHashMap<>();
    mappings.put("Map<String, Object>", "Properties");
    mappings.put("Map<String, String>", "StringProperties");
    mappings.put("Map<String, Webhook>", "WebhookMap");
    mappings.put("Map<String, Archive>", "ArchiveMap");
    mappings.put("Map<String, Jlink>", "JlinkMap");
    mappings.put("Map<String, Jpackage>", "JpackageMap");
    mappings.put("Map<String, NativeImage>", "NativeImageMap");
    mappings.put("Map<String, Distribution>", "DistributionMap");
    mappings.put("Map<String, DockerSpec>", "DockerSpecMap");
    mappings.put("Map<String, Artifactory>", "ArtifactoryMap");
    mappings.put("Map<String, Http>", "HttpMap");
    mappings.put("Map<String, S3>", "S3Map");
    try {
        SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(SchemaVersion.DRAFT_2019_09, OptionPreset.PLAIN_JSON);
        configBuilder.getObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
        configBuilder.with(Option.FORBIDDEN_ADDITIONAL_PROPERTIES_BY_DEFAULT);
        configBuilder.with(Option.DEFINITION_FOR_MAIN_SCHEMA);
        configBuilder.with(Option.DEFINITIONS_FOR_ALL_OBJECTS);
        JacksonModule jacksonModule = new JacksonModule();
        configBuilder.with(jacksonModule);
        configBuilder.forTypesInGeneral().withDescriptionResolver(scope -> scope.getType().getErasedType() == JReleaserModel.class ? String.format("JReleaser %s", JReleaserVersion.getPlainVersion()) : null).withPatternPropertiesResolver(scope -> {
            if (scope.getType().isInstanceOf(Map.class)) {
                ResolvedType type = scope.getTypeParameterFor(Map.class, 1);
                if (type.getErasedType() != String.class && type.getErasedType() != Object.class) {
                    return singletonMap("^[a-zA-Z-]+$", type);
                }
            }
            return null;
        }).withAdditionalPropertiesResolver(scope -> {
            if (scope.getType().isInstanceOf(Map.class)) {
                ResolvedType type = scope.getTypeParameterFor(Map.class, 1);
                if (type.getErasedType() == String.class || type.getErasedType() == Object.class) {
                    return scope.getTypeParameterFor(Map.class, 0);
                }
            }
            return null;
        }).withDefinitionNamingStrategy(new DefaultSchemaDefinitionNamingStrategy() {

            @Override
            public String getDefinitionNameForKey(DefinitionKey key, SchemaGenerationContext context) {
                String definitionNameForKey = super.getDefinitionNameForKey(key, context);
                return mappings.getOrDefault(definitionNameForKey, definitionNameForKey);
            }
        });
        SchemaGeneratorConfig config = configBuilder.build();
        SchemaGenerator generator = new SchemaGenerator(config);
        JsonNode jsonSchema = generator.generateSchema(JReleaserModel.class);
        String fileName = String.format("jreleaser-%s-schema.json", JReleaserVersion.getPlainVersion());
        Path schemaPath = Paths.get(fileName);
        String json = configBuilder.getObjectMapper().writeValueAsString(jsonSchema);
        Files.write(schemaPath, json.getBytes(), CREATE, WRITE, TRUNCATE_EXISTING);
        parent().out.println("Schema written to " + schemaPath.toAbsolutePath());
    } catch (Exception e) {
        throw new JReleaserException($("ERROR_unexpected_error"), e);
    }
}
Also used : Option(com.github.victools.jsonschema.generator.Option) TRUNCATE_EXISTING(java.nio.file.StandardOpenOption.TRUNCATE_EXISTING) SchemaGeneratorConfigBuilder(com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder) JReleaserModel(org.jreleaser.model.JReleaserModel) ResolvedType(com.fasterxml.classmate.ResolvedType) SchemaVersion(com.github.victools.jsonschema.generator.SchemaVersion) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) JsonNode(com.fasterxml.jackson.databind.JsonNode) Collections.singletonMap(java.util.Collections.singletonMap) Path(java.nio.file.Path) CommandLine(picocli.CommandLine) WRITE(java.nio.file.StandardOpenOption.WRITE) Files(java.nio.file.Files) OptionPreset(com.github.victools.jsonschema.generator.OptionPreset) SchemaGenerationContext(com.github.victools.jsonschema.generator.SchemaGenerationContext) DefinitionKey(com.github.victools.jsonschema.generator.impl.DefinitionKey) SchemaGenerator(com.github.victools.jsonschema.generator.SchemaGenerator) DefaultSchemaDefinitionNamingStrategy(com.github.victools.jsonschema.generator.naming.DefaultSchemaDefinitionNamingStrategy) JReleaserVersion(org.jreleaser.model.JReleaserVersion) Paths(java.nio.file.Paths) SchemaGeneratorConfig(com.github.victools.jsonschema.generator.SchemaGeneratorConfig) CREATE(java.nio.file.StandardOpenOption.CREATE) JReleaserException(org.jreleaser.util.JReleaserException) SerializationFeature(com.fasterxml.jackson.databind.SerializationFeature) JacksonModule(com.github.victools.jsonschema.module.jackson.JacksonModule) Path(java.nio.file.Path) SchemaGenerationContext(com.github.victools.jsonschema.generator.SchemaGenerationContext) SchemaGenerator(com.github.victools.jsonschema.generator.SchemaGenerator) JsonNode(com.fasterxml.jackson.databind.JsonNode) DefaultSchemaDefinitionNamingStrategy(com.github.victools.jsonschema.generator.naming.DefaultSchemaDefinitionNamingStrategy) JacksonModule(com.github.victools.jsonschema.module.jackson.JacksonModule) JReleaserException(org.jreleaser.util.JReleaserException) LinkedHashMap(java.util.LinkedHashMap) JReleaserException(org.jreleaser.util.JReleaserException) SchemaGeneratorConfig(com.github.victools.jsonschema.generator.SchemaGeneratorConfig) SchemaGeneratorConfigBuilder(com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder) JReleaserModel(org.jreleaser.model.JReleaserModel) DefinitionKey(com.github.victools.jsonschema.generator.impl.DefinitionKey) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) Collections.singletonMap(java.util.Collections.singletonMap) ResolvedType(com.fasterxml.classmate.ResolvedType)

Example 3 with JacksonModule

use of com.github.victools.jsonschema.module.jackson.JacksonModule in project kestra by kestra-io.

the class JsonSchemaGenerator method build.

protected <T> void build(SchemaGeneratorConfigBuilder builder, Class<? extends T> cls) {
    builder.with(new JacksonModule()).with(new JavaxValidationModule(JavaxValidationOption.NOT_NULLABLE_FIELD_IS_REQUIRED, JavaxValidationOption.INCLUDE_PATTERN_EXPRESSIONS)).with(new Swagger2Module()).with(Option.DEFINITIONS_FOR_ALL_OBJECTS).with(Option.DEFINITION_FOR_MAIN_SCHEMA).with(Option.PLAIN_DEFINITION_KEYS).with(Option.ALLOF_CLEANUP_AT_THE_END);
    // default value
    builder.forFields().withDefaultResolver(this::defaults);
    // def name
    builder.forTypesInGeneral().withDefinitionNamingStrategy(new DefaultSchemaDefinitionNamingStrategy() {

        @Override
        public String getDefinitionNameForKey(DefinitionKey key, SchemaGenerationContext context) {
            TypeContext typeContext = context.getTypeContext();
            ResolvedType type = key.getType();
            return typeContext.getFullTypeDescription(type);
        }

        @Override
        public String adjustNullableName(DefinitionKey key, String definitionName, SchemaGenerationContext context) {
            return definitionName;
        }
    });
    // inline some type
    builder.forTypesInGeneral().withCustomDefinitionProvider(new CustomDefinitionProviderV2() {

        @Override
        public CustomDefinition provideCustomSchemaDefinition(ResolvedType javaType, SchemaGenerationContext context) {
            if (javaType.isInstanceOf(Map.class) || javaType.isInstanceOf(Enum.class)) {
                ObjectNode definition = context.createStandardDefinition(javaType, this);
                return new CustomDefinition(definition, true);
            } else if (javaType.isInstanceOf(Duration.class)) {
                ObjectNode definitionReference = context.createDefinitionReference(context.getTypeContext().resolve(String.class)).put("format", "duration");
                return new CustomDefinition(definitionReference, true);
            } else {
                return null;
            }
        }
    });
    // PluginProperty $dynamic && deprecated swagger properties
    builder.forFields().withInstanceAttributeOverride((memberAttributes, member, context) -> {
        PluginProperty pluginPropertyAnnotation = member.getAnnotation(PluginProperty.class);
        if (pluginPropertyAnnotation != null) {
            memberAttributes.put("$dynamic", pluginPropertyAnnotation.dynamic());
        }
        Schema schema = member.getAnnotation(Schema.class);
        if (schema != null && schema.deprecated()) {
            memberAttributes.put("$deprecated", true);
        }
    });
    // Add Plugin annotation special docs
    builder.forTypesInGeneral().withTypeAttributeOverride((collectedTypeAttributes, scope, context) -> {
        Plugin pluginAnnotation = scope.getType().getErasedType().getAnnotation(Plugin.class);
        if (pluginAnnotation != null) {
            List<ObjectNode> examples = Arrays.stream(pluginAnnotation.examples()).map(example -> context.getGeneratorConfig().createObjectNode().put("full", example.full()).put("code", String.join("\n", example.code())).put("lang", example.lang()).put("title", example.title())).collect(Collectors.toList());
            if (examples.size() > 0) {
                collectedTypeAttributes.set("$examples", context.getGeneratorConfig().createArrayNode().addAll(examples));
            }
        }
    });
    // PluginProperty additionalProperties
    builder.forFields().withAdditionalPropertiesResolver(target -> {
        PluginProperty pluginPropertyAnnotation = target.getAnnotation(PluginProperty.class);
        if (pluginPropertyAnnotation != null) {
            return pluginPropertyAnnotation.additionalProperties();
        }
        return Object.class;
    });
}
Also used : JavaxValidationModule(com.github.victools.jsonschema.module.javax.validation.JavaxValidationModule) java.util(java.util) com.github.victools.jsonschema.generator(com.github.victools.jsonschema.generator) Plugin(io.kestra.core.models.annotations.Plugin) JacksonMapper(io.kestra.core.serializers.JacksonMapper) JavaxValidationOption(com.github.victools.jsonschema.module.javax.validation.JavaxValidationOption) ResolvedType(com.fasterxml.classmate.ResolvedType) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) Output(io.kestra.core.models.tasks.Output) Nullable(io.micronaut.core.annotation.Nullable) Duration(java.time.Duration) JsonNode(com.fasterxml.jackson.databind.JsonNode) Schema(io.swagger.v3.oas.annotations.media.Schema) java.lang.reflect(java.lang.reflect) ImmutableMap(com.google.common.collect.ImmutableMap) Predicate(java.util.function.Predicate) DefinitionKey(com.github.victools.jsonschema.generator.impl.DefinitionKey) Singleton(jakarta.inject.Singleton) Swagger2Module(com.github.victools.jsonschema.module.swagger2.Swagger2Module) Collectors(java.util.stream.Collectors) TextNode(com.fasterxml.jackson.databind.node.TextNode) PluginProperty(io.kestra.core.models.annotations.PluginProperty) DefaultSchemaDefinitionNamingStrategy(com.github.victools.jsonschema.generator.naming.DefaultSchemaDefinitionNamingStrategy) Task(io.kestra.core.models.tasks.Task) JacksonModule(com.github.victools.jsonschema.module.jackson.JacksonModule) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) Schema(io.swagger.v3.oas.annotations.media.Schema) JavaxValidationModule(com.github.victools.jsonschema.module.javax.validation.JavaxValidationModule) Swagger2Module(com.github.victools.jsonschema.module.swagger2.Swagger2Module) DefaultSchemaDefinitionNamingStrategy(com.github.victools.jsonschema.generator.naming.DefaultSchemaDefinitionNamingStrategy) JacksonModule(com.github.victools.jsonschema.module.jackson.JacksonModule) PluginProperty(io.kestra.core.models.annotations.PluginProperty) DefinitionKey(com.github.victools.jsonschema.generator.impl.DefinitionKey) ResolvedType(com.fasterxml.classmate.ResolvedType) Plugin(io.kestra.core.models.annotations.Plugin)

Example 4 with JacksonModule

use of com.github.victools.jsonschema.module.jackson.JacksonModule in project alfresco-java-sdk by Alfresco.

the class JsonSchemaGeneratorTest method getConfigBuilder.

private SchemaGeneratorConfigBuilder getConfigBuilder(final EventEntry entry) {
    final JacksonModule module = new JacksonModule(JacksonOption.RESPECT_JSONPROPERTY_ORDER);
    final SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(SchemaVersion.DRAFT_2019_09, OptionPreset.PLAIN_JSON).with(module);
    configBuilder.forTypesInGeneral().withSubtypeResolver((declaredType, generationContext) -> {
        if (declaredType.getErasedType() == Resource.class) {
            final TypeContext typeContext = generationContext.getTypeContext();
            switch(entry) {
                case NODE_ENTRY:
                    return List.of(typeContext.resolveSubtype(declaredType, NodeResource.class));
                case CHILD_ASSOC_ENTRY:
                    return List.of(typeContext.resolveSubtype(declaredType, ChildAssociationResource.class));
                case PEER_ASSOC_ENTRY:
                    return List.of(typeContext.resolveSubtype(declaredType, PeerAssociationResource.class));
            }
        }
        if (declaredType.getErasedType() == DataAttributes.class) {
            final TypeContext typeContext = generationContext.getTypeContext();
            if (entry == EventEntry.NODE_UPDATED_ENTRY) {
                return List.of(typeContext.resolveSubtype(declaredType, EventDataWithResourceBefore.class));
            } else {
                return List.of(typeContext.resolveSubtype(declaredType, EventDataWithoutResourceBefore.class));
            }
        }
        return null;
    });
    configBuilder.forFields().withTargetTypeOverridesResolver(field -> {
        if (field.getDeclaredType().getErasedType() == URI.class) {
            return Stream.of(String.class).map(specificSubtype -> field.getContext().resolve(String.class)).collect(Collectors.toList());
        }
        return null;
    });
    configBuilder.forFields().withRequiredCheck(field -> {
        final Required annotation = field.getAnnotation(Required.class);
        return (annotation != null);
    });
    return configBuilder;
}
Also used : NodeResource(org.alfresco.event.sdk.model.v1.model.schema.NodeResource) TypeContext(com.github.victools.jsonschema.generator.TypeContext) Required(org.alfresco.event.sdk.model.v1.model.schema.Required) SchemaGeneratorConfigBuilder(com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder) SchemaVersion(com.github.victools.jsonschema.generator.SchemaVersion) NodeResource(org.alfresco.event.sdk.model.v1.model.schema.NodeResource) RepoEvent(org.alfresco.event.sdk.model.v1.model.schema.RepoEvent) OutputStreamWriter(java.io.OutputStreamWriter) JsonNode(com.fasterxml.jackson.databind.JsonNode) URI(java.net.URI) PrintWriter(java.io.PrintWriter) DataAttributes(org.alfresco.event.sdk.model.v1.model.DataAttributes) OptionPreset(com.github.victools.jsonschema.generator.OptionPreset) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) Test(org.junit.Test) SchemaGenerator(com.github.victools.jsonschema.generator.SchemaGenerator) EventDataWithResourceBefore(org.alfresco.event.sdk.model.v1.model.schema.EventDataWithResourceBefore) Collectors(java.util.stream.Collectors) File(java.io.File) StandardCharsets(java.nio.charset.StandardCharsets) EventDataWithoutResourceBefore(org.alfresco.event.sdk.model.v1.model.schema.EventDataWithoutResourceBefore) List(java.util.List) Stream(java.util.stream.Stream) JacksonOption(com.github.victools.jsonschema.module.jackson.JacksonOption) SchemaGeneratorConfig(com.github.victools.jsonschema.generator.SchemaGeneratorConfig) ChildAssociationResource(org.alfresco.event.sdk.model.v1.model.schema.ChildAssociationResource) Resource(org.alfresco.event.sdk.model.v1.model.Resource) PeerAssociationResource(org.alfresco.event.sdk.model.v1.model.schema.PeerAssociationResource) JacksonModule(com.github.victools.jsonschema.module.jackson.JacksonModule) PeerAssociationResource(org.alfresco.event.sdk.model.v1.model.schema.PeerAssociationResource) Required(org.alfresco.event.sdk.model.v1.model.schema.Required) SchemaGeneratorConfigBuilder(com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder) ChildAssociationResource(org.alfresco.event.sdk.model.v1.model.schema.ChildAssociationResource) EventDataWithoutResourceBefore(org.alfresco.event.sdk.model.v1.model.schema.EventDataWithoutResourceBefore) TypeContext(com.github.victools.jsonschema.generator.TypeContext) JacksonModule(com.github.victools.jsonschema.module.jackson.JacksonModule) EventDataWithResourceBefore(org.alfresco.event.sdk.model.v1.model.schema.EventDataWithResourceBefore)

Aggregations

JacksonModule (com.github.victools.jsonschema.module.jackson.JacksonModule)4 JsonNode (com.fasterxml.jackson.databind.JsonNode)3 ResolvedType (com.fasterxml.classmate.ResolvedType)2 OptionPreset (com.github.victools.jsonschema.generator.OptionPreset)2 SchemaGenerator (com.github.victools.jsonschema.generator.SchemaGenerator)2 SchemaGeneratorConfig (com.github.victools.jsonschema.generator.SchemaGeneratorConfig)2 SchemaGeneratorConfigBuilder (com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder)2 SchemaVersion (com.github.victools.jsonschema.generator.SchemaVersion)2 DefinitionKey (com.github.victools.jsonschema.generator.impl.DefinitionKey)2 DefaultSchemaDefinitionNamingStrategy (com.github.victools.jsonschema.generator.naming.DefaultSchemaDefinitionNamingStrategy)2 JacksonOption (com.github.victools.jsonschema.module.jackson.JacksonOption)2 Collectors (java.util.stream.Collectors)2 SerializationFeature (com.fasterxml.jackson.databind.SerializationFeature)1 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)1 TextNode (com.fasterxml.jackson.databind.node.TextNode)1 com.github.victools.jsonschema.generator (com.github.victools.jsonschema.generator)1 Option (com.github.victools.jsonschema.generator.Option)1 SchemaGenerationContext (com.github.victools.jsonschema.generator.SchemaGenerationContext)1 TypeContext (com.github.victools.jsonschema.generator.TypeContext)1 JavaxValidationModule (com.github.victools.jsonschema.module.javax.validation.JavaxValidationModule)1