This is an automated email from the ASF dual-hosted git repository. lburgazzoli pushed a commit to branch main in repository https://gitbox.apache.org/repos/asf/camel-k-runtime.git
commit 38defedf4bc50db54a9d911670888de57eff5f1b Author: Luca Burgazzoli <lburgazz...@gmail.com> AuthorDate: Wed Aug 17 16:48:27 2022 +0200 chore: remove deprecated yaml dsl mojos --- pom.xml | 4 - .../tooling/maven/GenerateYamlEndpointsSchema.java | 146 ------ .../maven/GenerateYamlLoaderSupportClasses.java | 272 ---------- .../maven/GenerateYamlParserSupportClasses.java | 290 ----------- .../camel/k/tooling/maven/GenerateYamlSchema.java | 564 --------------------- .../camel/k/tooling/maven/GenerateYamlSupport.java | 176 ------- .../k/tooling/maven/support/IndexerSupport.java | 114 ----- .../k/tooling/maven/support/MavenSupport.java | 24 - .../k/tooling/maven/support/ToolingSupport.java | 58 --- .../processors/GenerateYamlSupportClassesTest.java | 57 --- 10 files changed, 1705 deletions(-) diff --git a/pom.xml b/pom.xml index 53e00e87..3eea8ea4 100644 --- a/pom.xml +++ b/pom.xml @@ -50,10 +50,6 @@ <groovy-version>3.0.12</groovy-version> <immutables-version>2.9.0</immutables-version> - <!-- overridden camel dependencies versions --> - <json-schema-validator-version>2.2.14</json-schema-validator-version> - <jandex-version>2.4.3.Final</jandex-version> - <!-- plugins --> <gmavenplus-plugin-version>1.13.1</gmavenplus-plugin-version> <maven-compiler-plugin-version>3.10.1</maven-compiler-plugin-version> diff --git a/support/camel-k-maven-plugin/src/main/java/org/apache/camel/k/tooling/maven/GenerateYamlEndpointsSchema.java b/support/camel-k-maven-plugin/src/main/java/org/apache/camel/k/tooling/maven/GenerateYamlEndpointsSchema.java deleted file mode 100644 index f4b42987..00000000 --- a/support/camel-k-maven-plugin/src/main/java/org/apache/camel/k/tooling/maven/GenerateYamlEndpointsSchema.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.camel.k.tooling.maven; - - -import java.io.File; -import java.io.IOException; -import java.util.Collection; -import java.util.Comparator; -import java.util.List; -import java.util.Objects; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ObjectNode; -import org.apache.camel.catalog.CamelCatalog; -import org.apache.camel.catalog.DefaultCamelCatalog; -import org.apache.camel.k.tooling.maven.support.ToolingSupport; -import org.apache.camel.tooling.model.ComponentModel; -import org.apache.camel.util.StringHelper; -import org.apache.maven.plugin.MojoFailureException; -import org.apache.maven.plugins.annotations.LifecyclePhase; -import org.apache.maven.plugins.annotations.Mojo; -import org.apache.maven.plugins.annotations.Parameter; -import org.apache.maven.plugins.annotations.ResolutionScope; - -@Mojo( - name = "generate-yaml-endpoints-schema", - inheritByDefault = false, - defaultPhase = LifecyclePhase.GENERATE_SOURCES, - requiresDependencyResolution = ResolutionScope.COMPILE, - threadSafe = true, - requiresProject = false) -public class GenerateYamlEndpointsSchema extends GenerateYamlSupport { - @Parameter - protected List<String> bannedDefinitions; - @Parameter(property = "camel.k.yaml.schema", defaultValue = "${project.build.directory}/yaml-${project.version}.json") - private File outputFile; - - private ObjectNode definitions; - - @Override - public void execute() throws MojoFailureException { - final ObjectMapper mapper = new ObjectMapper(); - final ObjectNode root = mapper.createObjectNode(); - - // Schema - root.put("$schema", "http://json-schema.org/draft-04/schema#"); - root.put("type", "object"); - - // Schema sections - this.definitions = root.putObject("definitions"); - - final CamelCatalog catalog = new DefaultCamelCatalog(); - for (String componentName : catalog.findComponentNames()) { - ComponentModel component = catalog.componentModel(componentName); - if (!definitions.has(component.getScheme())) { - ObjectNode node = definitions.putObject(component.getScheme()); - node.put("type", "object"); - - processEndpointOption(node, component.getEndpointPathOptions()); - processEndpointOption(node, component.getEndpointParameterOptions()); - } - - if (component.getAlternativeSchemes() != null) { - for (String scheme: component.getAlternativeSchemes().split(",")) { - if (!definitions.has(scheme)) { - definitions.putObject(scheme) - .put("type", "object") - .put("$ref", "#/definitions/" + component.getScheme()); - } - } - } - } - - try { - ToolingSupport.mkparents(outputFile); - - mapper.writerWithDefaultPrettyPrinter().writeValue(outputFile, root); - } catch (IOException e) { - throw new MojoFailureException(e.getMessage(), e); - } - } - - private void processEndpointOption(ObjectNode root, Collection<ComponentModel.EndpointOptionModel> options) { - options.stream() - .sorted(Comparator.comparing(ComponentModel.EndpointOptionModel::getName)) - .forEach(option -> { - if (option.isRequired()) { - root.withArray("required").add(option.getName()); - } - - String name = StringHelper.camelCaseToDash(option.getName()); - ObjectNode node = root.with("properties").putObject(name); - - processEndpointOption(node, option); - }); - } - - private void processEndpointOption(ObjectNode root, ComponentModel.EndpointOptionModel option) { - if (option.getDescription() != null) { - root.put("description", option.getDescription()); - } - if (option.getDefaultValue() != null) { - root.put("default", Objects.toString(option.getDefaultValue())); - } - if (option.getEnums() != null) { - option.getEnums().forEach(value -> root.withArray("enum").add(value)); - } - - switch (option.getType()) { - case "string": - case "object": - case "array": - case "duration": - root.put("type", "string"); - break; - case "boolean": - root.put("type", "boolean"); - break; - case "integer": - root.put("type", "integer"); - break; - case "number": - root.put("type", "number"); - break; - default: - throw new IllegalArgumentException( - "Unable to determine type for name: " + option.getName() + ", type: " + option.getType()); - - } - } -} diff --git a/support/camel-k-maven-plugin/src/main/java/org/apache/camel/k/tooling/maven/GenerateYamlLoaderSupportClasses.java b/support/camel-k-maven-plugin/src/main/java/org/apache/camel/k/tooling/maven/GenerateYamlLoaderSupportClasses.java deleted file mode 100644 index 6ba81af3..00000000 --- a/support/camel-k-maven-plugin/src/main/java/org/apache/camel/k/tooling/maven/GenerateYamlLoaderSupportClasses.java +++ /dev/null @@ -1,272 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.camel.k.tooling.maven; - - -import java.io.IOException; -import java.nio.file.Paths; -import java.util.Comparator; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import javax.lang.model.element.Modifier; - -import com.fasterxml.jackson.core.Version; -import com.fasterxml.jackson.databind.Module; -import com.squareup.javapoet.ClassName; -import com.squareup.javapoet.CodeBlock; -import com.squareup.javapoet.JavaFile; -import com.squareup.javapoet.MethodSpec; -import com.squareup.javapoet.TypeSpec; -import org.apache.camel.catalog.CamelCatalog; -import org.apache.camel.catalog.DefaultCamelCatalog; -import org.apache.camel.k.tooling.maven.support.ToolingSupport; -import org.apache.camel.util.AntPathMatcher; -import org.apache.camel.util.StringHelper; -import org.apache.maven.plugin.MojoFailureException; -import org.apache.maven.plugins.annotations.LifecyclePhase; -import org.apache.maven.plugins.annotations.Mojo; -import org.apache.maven.plugins.annotations.Parameter; -import org.apache.maven.plugins.annotations.ResolutionScope; -import org.jboss.jandex.AnnotationInstance; -import org.jboss.jandex.AnnotationValue; -import org.jboss.jandex.ClassInfo; - -@Mojo( - name = "generate-yaml-loader-support-classes", - inheritByDefault = false, - defaultPhase = LifecyclePhase.GENERATE_SOURCES, - requiresDependencyResolution = ResolutionScope.COMPILE, - threadSafe = true, - requiresProject = false) -public class GenerateYamlLoaderSupportClasses extends GenerateYamlSupport { - @Parameter - protected List<String> bannedDefinitions; - @Parameter(defaultValue = "${project.build.directory}/generated-sources/camel") - protected String output; - - @Override - public void execute() throws MojoFailureException { - try { - JavaFile.builder("org.apache.camel.k.loader.yaml", generateJacksonModule()) - .indent(" ") - .build() - .writeTo(Paths.get(output)); - JavaFile.builder("org.apache.camel.k.loader.yaml", generateReifiers()) - .indent(" ") - .build() - .writeTo(Paths.get(output)); - JavaFile.builder("org.apache.camel.k.loader.yaml", generateResolver()) - .indent(" ") - .build() - .writeTo(Paths.get(output)); - } catch (IOException e) { - throw new MojoFailureException(e.getMessage(), e); - } - } - - public final TypeSpec generateJacksonModule() { - TypeSpec.Builder type = TypeSpec.classBuilder("YamlModule"); - type.addModifiers(Modifier.PUBLIC, Modifier.FINAL); - type.superclass(Module.class); - type.addMethod( - MethodSpec.methodBuilder("getModuleName") - .addModifiers(Modifier.PUBLIC) - .addAnnotation(Override.class) - .returns(String.class) - .addCode(CodeBlock.builder().addStatement("return $S", "camel-yaml").build()) - .build() - ); - type.addMethod( - MethodSpec.methodBuilder("version") - .addModifiers(Modifier.PUBLIC) - .addAnnotation(Override.class) - .returns(Version.class) - .addCode(CodeBlock.builder().addStatement("return $L", "Version.unknownVersion()").build()) - .build() - ); - - MethodSpec.Builder mb = MethodSpec.methodBuilder("setupModule") - .addModifiers(Modifier.PUBLIC) - .addParameter(Module.SetupContext.class, "context"); - - definitions(EXPRESSION_DEFINITION_CLASS).forEach( - (k, v) -> mb.addStatement("context.registerSubtypes(new com.fasterxml.jackson.databind.jsontype.NamedType($L.class, $S))", v.name().toString(), k) - ); - definitions(DATAFORMAT_DEFINITION_CLASS).forEach( - (k, v) -> mb.addStatement("context.registerSubtypes(new com.fasterxml.jackson.databind.jsontype.NamedType($L.class, $S))", v.name().toString(), k) - ); - definitions(LOAD_BALANCE_DEFINITION_CLASS).forEach( - (k, v) -> mb.addStatement("context.registerSubtypes(new com.fasterxml.jackson.databind.jsontype.NamedType($L.class, $S))", v.name().toString(), k) - ); - - annotated(YAML_MIXIN_ANNOTATION).forEach(i -> { - final AnnotationInstance annotation = i.classAnnotation(YAML_MIXIN_ANNOTATION); - final AnnotationValue targets = annotation.value("value"); - - String name = i.toString(); - if (i.nestingType() == ClassInfo.NestingType.INNER) { - name = i.enclosingClass().toString() + "." + i.simpleName(); - } - - if (targets != null) { - for (String target: targets.asStringArray()) { - mb.addStatement("context.setMixInAnnotations($L.class, $L.class);", target, name); - } - } - }); - - - type.addMethod(mb.build()); - - return type.build(); - } - - public final TypeSpec generateReifiers() { - TypeSpec.Builder type = TypeSpec.classBuilder("YamlReifiers"); - type.addModifiers(Modifier.PUBLIC, Modifier.FINAL); - - MethodSpec.Builder mb = MethodSpec.methodBuilder("registerReifiers") - .addModifiers(Modifier.PUBLIC) - .addModifiers(Modifier.STATIC); - - annotated(YAML_NODE_DEFINITION_ANNOTATION).forEach(i -> { - final AnnotationInstance annotation = i.classAnnotation(YAML_NODE_DEFINITION_ANNOTATION); - final AnnotationValue reifiers = annotation.value("reifiers"); - - if (reifiers != null) { - String name = i.toString(); - if (i.nestingType() == ClassInfo.NestingType.INNER) { - name = i.enclosingClass().toString() + "." + i.simpleName(); - } - - for (String reifier: reifiers.asStringArray()) { - mb.addStatement("org.apache.camel.reifier.ProcessorReifier.registerReifier($L.class, $L::new)", name, reifier); - } - } - }); - - type.addMethod(mb.build()); - - return type.build(); - } - - public final TypeSpec generateResolver() { - Set<String> ids = new HashSet<>(); - - MethodSpec.Builder mb = MethodSpec.methodBuilder("resolve") - .addAnnotation(Override.class) - .addModifiers(Modifier.PUBLIC) - .addParameter(ClassName.get("org.apache.camel", "CamelContext"), "camelContext") - .addParameter(ClassName.get("java.lang", "String"), "id") - .returns(ClassName.get("org.apache.camel.k.loader.yaml.spi", "StepParser")); - - mb.beginControlFlow("switch(id)"); - - mb.addComment("custom parsers"); - - annotated(YAML_STEP_PARSER_ANNOTATION) - .sorted(Comparator.comparing(i -> i.name().toString())) - .forEach( - i -> { - AnnotationValue id = i.classAnnotation(YAML_STEP_PARSER_ANNOTATION).value("id"); - if (id != null && ids.add(id.asString())) { - mb.beginControlFlow("case $S:", id.asString()); - mb.addStatement("return new $L()", i.name().toString()); - mb.endControlFlow(); - } - - AnnotationValue aliases = i.classAnnotation(YAML_STEP_PARSER_ANNOTATION).value("aliases"); - if (aliases != null) { - for (String alias : aliases.asStringArray()) { - if (ids.add(alias)) { - mb.beginControlFlow("case $S:", alias); - mb.addStatement("return new $L()", i.name().toString()); - mb.endControlFlow(); - } - } - } - } - ); - - mb.addComment("auto generated parsers"); - - annotated(XML_ROOT_ELEMENT_ANNOTATION_CLASS) - .forEach( - i -> { - AnnotationInstance meta = i.classAnnotation(METADATA_ANNOTATION); - AnnotationInstance root = i.classAnnotation(XML_ROOT_ELEMENT_ANNOTATION_CLASS); - - if (meta == null || root == null) { - return; - } - - AnnotationValue name = root.value("name"); - AnnotationValue label = meta.value("label"); - - if (name == null || label == null) { - return; - } - - if (bannedDefinitions != null) { - for (String bannedDefinition: bannedDefinitions) { - if (AntPathMatcher.INSTANCE.match(bannedDefinition.replace('.', '/'), i.name().toString('/'))) { - getLog().debug("Skipping definition: " + i.name().toString()); - return; - } - } - } - - Set<String> labels = Set.of(label.asString().split(",", -1)); - if (labels.contains("eip")) { - String id = StringHelper.camelCaseToDash(name.asString()); - if (ids.add(id)) { - mb.beginControlFlow("case $S:", id); - mb.addStatement("return new org.apache.camel.k.loader.yaml.parser.TypedProcessorStepParser($L.class)", i.name().toString()); - mb.endControlFlow(); - } - } - } - ); - - mb.addComment("endpoint dsl"); - - CamelCatalog catalog = new DefaultCamelCatalog(); - catalog.findComponentNames().stream() - .sorted() - .map(catalog::componentModel) - .flatMap(component -> ToolingSupport.combine(component.getScheme(), component.getAlternativeSchemes())) - .filter(ids::add) - .forEach(scheme -> { - mb.beginControlFlow("case $S:", scheme); - mb.addStatement("return new org.apache.camel.k.loader.yaml.parser.EndpointStepParser($S)", scheme); - mb.endControlFlow(); - }); - - mb.beginControlFlow("default:"); - mb.addStatement("return lookup(camelContext, id)"); - mb.endControlFlow(); - mb.endControlFlow(); - - return TypeSpec.classBuilder("YamlStepResolver") - .addModifiers(Modifier.PUBLIC, Modifier.FINAL) - .addSuperinterface(ClassName.get("org.apache.camel.k.loader.yaml.spi", "StepParser.Resolver")) - .addMethod(mb.build()) - .build(); - } -} diff --git a/support/camel-k-maven-plugin/src/main/java/org/apache/camel/k/tooling/maven/GenerateYamlParserSupportClasses.java b/support/camel-k-maven-plugin/src/main/java/org/apache/camel/k/tooling/maven/GenerateYamlParserSupportClasses.java deleted file mode 100644 index 88b8a835..00000000 --- a/support/camel-k-maven-plugin/src/main/java/org/apache/camel/k/tooling/maven/GenerateYamlParserSupportClasses.java +++ /dev/null @@ -1,290 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.camel.k.tooling.maven; - - -import java.io.IOException; -import java.nio.file.Paths; -import java.util.Map; - -import javax.lang.model.element.Modifier; - -import com.fasterxml.jackson.annotation.JsonAlias; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.squareup.javapoet.AnnotationSpec; -import com.squareup.javapoet.ClassName; -import com.squareup.javapoet.CodeBlock; -import com.squareup.javapoet.JavaFile; -import com.squareup.javapoet.MethodSpec; -import com.squareup.javapoet.ParameterizedTypeName; -import com.squareup.javapoet.TypeSpec; -import org.apache.camel.catalog.CamelCatalog; -import org.apache.camel.catalog.DefaultCamelCatalog; -import org.apache.camel.k.tooling.maven.support.ToolingSupport; -import org.apache.camel.model.DataFormatDefinition; -import org.apache.camel.model.LoadBalancerDefinition; -import org.apache.camel.model.language.ExpressionDefinition; -import org.apache.camel.util.StringHelper; -import org.apache.maven.plugin.MojoFailureException; -import org.apache.maven.plugins.annotations.LifecyclePhase; -import org.apache.maven.plugins.annotations.Mojo; -import org.apache.maven.plugins.annotations.Parameter; -import org.apache.maven.plugins.annotations.ResolutionScope; - -@Mojo( - name = "generate-yaml-parser-support-classes", - inheritByDefault = false, - defaultPhase = LifecyclePhase.GENERATE_SOURCES, - requiresDependencyResolution = ResolutionScope.COMPILE, - threadSafe = true) -public class GenerateYamlParserSupportClasses extends GenerateYamlSupport { - @Parameter(defaultValue = "${project.build.directory}/generated-sources/camel") - protected String output; - - @Override - public void execute() throws MojoFailureException { - try { - JavaFile.builder("org.apache.camel.k.loader.yaml.parser", generateHasExpression()) - .indent(" ") - .build() - .writeTo(Paths.get(output)); - JavaFile.builder("org.apache.camel.k.loader.yaml.parser", generateHasDataFormat()) - .indent(" ") - .build() - .writeTo(Paths.get(output)); - JavaFile.builder("org.apache.camel.k.loader.yaml.parser", generateHasLoadBalancerType()) - .indent(" ") - .build() - .writeTo(Paths.get(output)); - JavaFile.builder("org.apache.camel.k.loader.yaml.parser", generateHasEndpointConsumer()) - .indent(" ") - .build() - .writeTo(Paths.get(output)); - JavaFile.builder("org.apache.camel.k.loader.yaml.parser", generateHasEndpointProducer()) - .indent(" ") - .build() - .writeTo(Paths.get(output)); - } catch (IOException e) { - throw new MojoFailureException(e.getMessage(), e); - } - } - - public final TypeSpec generateHasExpression() { - TypeSpec.Builder type = TypeSpec.interfaceBuilder("HasExpression"); - type.addModifiers(Modifier.PUBLIC); - type.addMethod( - MethodSpec.methodBuilder("setExpression") - .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT) - .addParameter(ExpressionDefinition.class, "expressionDefinition") - .addAnnotation( - AnnotationSpec.builder(JsonTypeInfo.class) - .addMember("use", "$L", "JsonTypeInfo.Id.NAME") - .addMember("include", "$L", "JsonTypeInfo.As.WRAPPER_OBJECT") - .build()) - .build() - ); - - type.addMethod( - MethodSpec.methodBuilder("getExpression") - .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT) - .returns(ExpressionDefinition.class) - .build() - ); - - definitions(EXPRESSION_DEFINITION_CLASS).forEach( - (k, v) -> { - String name = k; - name = StringHelper.capitalize(name); - name = name.replace("_", ""); - name = name.replace("-", ""); - - type.addMethod(MethodSpec.methodBuilder("set" + name) - .addAnnotation( - AnnotationSpec.builder(JsonAlias.class).addMember("value", "$S", k).build()) - .addModifiers(Modifier.PUBLIC, Modifier.DEFAULT) - .addParameter(loadClass(v), "definition") - .addCode( - CodeBlock.builder() - .beginControlFlow("if (getExpression() != null)") - .addStatement("throw new IllegalArgumentException(\"And expression has already been set\")") - .endControlFlow() - .addStatement("setExpression(definition);").build()) - .build() - ); - } - ); - - return type.build(); - } - - public final TypeSpec generateHasDataFormat() { - TypeSpec.Builder type = TypeSpec.interfaceBuilder("HasDataFormat"); - type.addModifiers(Modifier.PUBLIC); - type.addMethod( - MethodSpec.methodBuilder("setDataFormatType") - .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT) - .addParameter(DataFormatDefinition.class, "dataFormatType") - .addAnnotation( - AnnotationSpec.builder(JsonAlias.class). - addMember("value", "{$S, $S}", "data-format-type", "data-format") - .build()) - .addAnnotation( - AnnotationSpec.builder(JsonTypeInfo.class) - .addMember("use", "$L", "JsonTypeInfo.Id.NAME") - .addMember("include", "$L", "JsonTypeInfo.As.WRAPPER_OBJECT") - .build()) - .build() - ); - - type.addMethod( - MethodSpec.methodBuilder("getDataFormatType") - .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT) - .returns(DataFormatDefinition.class) - .build() - ); - - definitions(DATAFORMAT_DEFINITION_CLASS).forEach( - (k, v) -> { - String name = k; - name = StringHelper.capitalize(name); - name = name.replace("_", ""); - name = name.replace("-", ""); - - type.addMethod(MethodSpec.methodBuilder("set" + name) - .addAnnotation( - AnnotationSpec.builder(JsonAlias.class).addMember("value", "$S", k).build()) - .addModifiers(Modifier.PUBLIC, Modifier.DEFAULT) - .addParameter(loadClass(v), "definition") - .addCode( - CodeBlock.builder() - .beginControlFlow("if (getDataFormatType() != null)") - .addStatement("throw new IllegalArgumentException(\"A data format has already been set\")") - .endControlFlow() - .addStatement("setDataFormatType(definition);") - .build()) - .build() - ); - } - ); - - return type.build(); - } - - public final TypeSpec generateHasLoadBalancerType() { - TypeSpec.Builder type = TypeSpec.interfaceBuilder("HasLoadBalancerType"); - type.addModifiers(Modifier.PUBLIC); - type.addMethod( - MethodSpec.methodBuilder("setLoadBalancerType") - .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT) - .addParameter(LoadBalancerDefinition.class, "loadbalancer") - .addAnnotation( - AnnotationSpec.builder(JsonTypeInfo.class) - .addMember("use", "$L", "JsonTypeInfo.Id.NAME") - .addMember("include", "$L", "JsonTypeInfo.As.WRAPPER_OBJECT") - .build()) - .build() - ); - - type.addMethod( - MethodSpec.methodBuilder("getLoadBalancerType") - .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT) - .returns(LoadBalancerDefinition.class) - .build() - ); - - definitions(LOAD_BALANCE_DEFINITION_CLASS).forEach( - (k, v) -> { - String name = k; - name = StringHelper.capitalize(name); - name = name.replace("_", ""); - name = name.replace("-", ""); - - type.addMethod(MethodSpec.methodBuilder("set" + name) - .addAnnotation( - AnnotationSpec.builder(JsonAlias.class).addMember("value", "$S", k).build()) - .addModifiers(Modifier.PUBLIC, Modifier.DEFAULT) - .addParameter(loadClass(v), "definition") - .addCode( - CodeBlock.builder() - .beginControlFlow("if (getLoadBalancerType() != null)") - .addStatement("throw new IllegalArgumentException(\"A load-balancer has already been set\")") - .endControlFlow() - .addStatement("setLoadBalancerType(definition);").build()) - .build() - ); - } - ); - - return type.build(); - } - - public final TypeSpec generateHasEndpointConsumer() { - TypeSpec.Builder type = TypeSpec.interfaceBuilder("HasEndpointConsumer"); - type.addModifiers(Modifier.PUBLIC); - type.addSuperinterface(ClassName.get("org.apache.camel.k.loader.yaml.spi", "HasEndpoint")); - - CamelCatalog catalog = new DefaultCamelCatalog(); - catalog.findComponentNames().stream() - .map(catalog::componentModel) - .filter(component -> !component.isProducerOnly()) - .flatMap(component -> ToolingSupport.combine(component.getScheme(), component.getAlternativeSchemes())) - .sorted() - .distinct() - .forEach(scheme -> generateHasEndpointProducer(scheme, type)); - - return type.build(); - } - - public final TypeSpec generateHasEndpointProducer() { - TypeSpec.Builder type = TypeSpec.interfaceBuilder("HasEndpointProducer"); - type.addModifiers(Modifier.PUBLIC); - type.addSuperinterface(ClassName.get("org.apache.camel.k.loader.yaml.spi", "HasEndpoint")); - - CamelCatalog catalog = new DefaultCamelCatalog(); - catalog.findComponentNames().stream() - .map(catalog::componentModel) - .filter(component -> !component.isConsumerOnly()) - .flatMap(component -> ToolingSupport.combine(component.getScheme(), component.getAlternativeSchemes())) - .sorted() - .distinct() - .forEach(scheme -> generateHasEndpointProducer(scheme, type)); - - return type.build(); - } - - private static void generateHasEndpointProducer(String scheme, TypeSpec.Builder type) { - String name = StringHelper.dashToCamelCase(scheme); - name = name.replaceAll("[^a-zA-Z0-9]", ""); - name = name.toLowerCase(); - - type.addMethod(MethodSpec.methodBuilder("set_" + name) - .addAnnotation(AnnotationSpec.builder(JsonProperty.class).addMember("value", "$S", scheme).build()) - .addModifiers(Modifier.PUBLIC, Modifier.DEFAULT) - .addParameter(ParameterizedTypeName.get(Map.class, String.class, Object.class), "parameters") - .addCode( - CodeBlock.builder() - .beginControlFlow("if (getEndpointScheme() != null)") - .addStatement("throw new IllegalArgumentException(\"And endpoint has already been set\")") - .endControlFlow() - .addStatement("setEndpointScheme($S);", scheme) - .addStatement("setParameters(parameters);") - .build()) - .build() - ); - } -} diff --git a/support/camel-k-maven-plugin/src/main/java/org/apache/camel/k/tooling/maven/GenerateYamlSchema.java b/support/camel-k-maven-plugin/src/main/java/org/apache/camel/k/tooling/maven/GenerateYamlSchema.java deleted file mode 100644 index c8b16851..00000000 --- a/support/camel-k-maven-plugin/src/main/java/org/apache/camel/k/tooling/maven/GenerateYamlSchema.java +++ /dev/null @@ -1,564 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.camel.k.tooling.maven; - - -import java.io.File; -import java.io.IOException; -import java.util.Collection; -import java.util.Comparator; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ArrayNode; -import com.fasterxml.jackson.databind.node.ObjectNode; -import org.apache.camel.k.tooling.maven.support.IndexerSupport; -import org.apache.camel.k.tooling.maven.support.MavenSupport; -import org.apache.camel.k.tooling.maven.support.ToolingSupport; -import org.apache.camel.util.AntPathMatcher; -import org.apache.camel.util.ObjectHelper; -import org.apache.camel.util.StringHelper; -import org.apache.maven.plugin.MojoFailureException; -import org.apache.maven.plugins.annotations.LifecyclePhase; -import org.apache.maven.plugins.annotations.Mojo; -import org.apache.maven.plugins.annotations.Parameter; -import org.apache.maven.plugins.annotations.ResolutionScope; -import org.jboss.jandex.AnnotationInstance; -import org.jboss.jandex.AnnotationValue; -import org.jboss.jandex.ClassInfo; -import org.jboss.jandex.DotName; -import org.jboss.jandex.FieldInfo; -import org.jboss.jandex.MethodInfo; -import org.jboss.jandex.ParameterizedType; -import org.jboss.jandex.Type; - -@Mojo( - name = "generate-yaml-schema", - inheritByDefault = false, - defaultPhase = LifecyclePhase.GENERATE_SOURCES, - requiresDependencyResolution = ResolutionScope.COMPILE, - threadSafe = true, - requiresProject = false) -public class GenerateYamlSchema extends GenerateYamlSupport { - @Parameter - protected List<String> bannedDefinitions; - @Parameter(property = "camel.k.yaml.schema", defaultValue = "${project.build.directory}/yaml-${project.version}.json") - private File outputFile; - - private ObjectNode items; - private ObjectNode definitions; - - @Override - public void execute() throws MojoFailureException { - final ObjectMapper mapper = new ObjectMapper(); - final ObjectNode root = mapper.createObjectNode(); - - // Schema - root.put("$schema", "http://json-schema.org/draft-04/schema#"); - root.put("type", "array"); - - // Schema sections - this.items = root.putObject("items"); - this.definitions = this.items.putObject("definitions"); - - definitions(EXPRESSION_DEFINITION_CLASS).entrySet().stream() - .sorted(Map.Entry.comparingByKey()) - .forEach(entry -> { - processType( - definitions.with(entry.getValue().name().toString()), - entry.getValue()); - - definitions.with("expressions") - .put("type", "object") - .with("properties") - .putObject(StringHelper.camelCaseToDash(entry.getKey())) - .put("$ref", "#/items/definitions/" + entry.getValue().name().toString()); - }); - definitions(DATAFORMAT_DEFINITION_CLASS).entrySet().stream() - .sorted(Map.Entry.comparingByKey()) - .forEach(entry -> { - processType( - definitions.with(entry.getValue().name().toString()), - entry.getValue()); - - definitions.with("dataformats") - .put("type", "object") - .with("properties") - .putObject(StringHelper.camelCaseToDash(entry.getKey())) - .put("$ref", "#/items/definitions/" + entry.getValue().name().toString()); - }); - - // custom node definitions - annotated(YAML_NODE_DEFINITION_ANNOTATION) - .sorted(Comparator.comparing(entry -> entry.name().toString())) - .forEach(i -> processType(definitions.with(i.name().toString()), i)); - - Set<String> ids = new HashSet<>(); - - implementors(ERROR_HANDLER_CLASS) - .sorted(Comparator.comparing(entry -> entry.name().toString())) - .forEach( - entry -> { - ObjectNode node = definitions.putObject(entry.name().toString()); - if (hasStringConstructor(entry)) { - ArrayNode anyOf = node.putArray("anyOf"); - anyOf.addObject() - .put("type", "string"); - - node = anyOf.addObject(); - } - - node.put("type", "object"); - - for (MethodInfo mi: IndexerSupport.methods(view.get(), entry)) { - if (mi.returnType().kind() != Type.Kind.VOID) { - continue; - } - if (mi.parameters().size() != 1) { - continue; - } - if (mi.parameters().get(0).kind() != Type.Kind.PRIMITIVE) { - continue; - } - if (!mi.name().startsWith("set")) { - continue; - } - - String methodName = StringHelper.after(mi.name(), "set"); - String propertyName = StringHelper.camelCaseToDash(methodName); - ObjectNode property = node.with("properties").with(propertyName); - - setJsonSchemaType(property, mi.parameters().get(0)); - } - } - ); - - // custom parsers - annotated(YAML_STEP_PARSER_ANNOTATION) - .sorted(Comparator.comparing(entry -> entry.name().toString())) - .forEach( - entry -> { - boolean schema = annotationValue(entry, YAML_STEP_PARSER_ANNOTATION, "schema") - .map(AnnotationValue::asBoolean) - .orElse(true); - - if (!schema) { - return; - } - - String stepId = annotationValue(entry, YAML_STEP_PARSER_ANNOTATION, "id") - .map(AnnotationValue::asString) - .orElseThrow(() -> new IllegalArgumentException("Missing id field")); - - if (!ids.add(stepId)) { - return; - } - - String model = annotationValue(entry, YAML_STEP_PARSER_ANNOTATION, "definition") - .map(AnnotationValue::asString) - .orElseThrow(() -> new IllegalArgumentException("Missing definitions field")); - - DotName name = DotName.createSimple(model); - - if (implementsInterface(entry, START_STEP_PARSER_CLASS)) { - items.put("maxProperties", 1); - items.with("properties") - .putObject(stepId) - .put("$ref", "#/items/definitions/" + name.toString()); - } - - if (implementsInterface(entry, PROCESSOR_STEP_PARSER_CLASS)) { - ObjectNode stepNode = definitions.with("step"); - stepNode.put("type", "object"); - stepNode.put("maxProperties", 1); - - stepNode.with("properties") - .putObject(stepId) - .put("$ref", "#/items/definitions/" + name.toString()); - } - } - ); - - // auto generated parsers - annotated(XML_ROOT_ELEMENT_ANNOTATION_CLASS) - .forEach( - i -> { - AnnotationInstance meta = i.classAnnotation(METADATA_ANNOTATION); - AnnotationInstance xmlRoot = i.classAnnotation(XML_ROOT_ELEMENT_ANNOTATION_CLASS); - - if (meta == null || xmlRoot == null) { - return; - } - - AnnotationValue name = xmlRoot.value("name"); - AnnotationValue label = meta.value("label"); - - if (name == null || label == null) { - return; - } - - if (bannedDefinitions != null) { - for (String bannedDefinition: bannedDefinitions) { - if (AntPathMatcher.INSTANCE.match(bannedDefinition.replace('.', '/'), i.name().toString('/'))) { - getLog().debug("Skipping definition: " + i.name().toString()); - return; - } - } - } - - Set<String> labels = Set.of(label.asString().split(",", -1)); - if (labels.contains("eip")) { - String stepId = StringHelper.camelCaseToDash(name.asString()); - if (!ids.add(stepId)) { - return; - } - - processType(definitions.with(i.name().toString()), i); - - ObjectNode stepNode = definitions.with("step"); - stepNode.put("type", "object"); - stepNode.put("maxProperties", 1); - - stepNode.with("properties") - .putObject(stepId) - .put("$ref", "#/items/definitions/" + i.name().toString()); - } - } - ); - - try { - ToolingSupport.mkparents(outputFile); - - mapper.writerWithDefaultPrettyPrinter().writeValue(outputFile, root); - } catch (IOException e) { - throw new MojoFailureException(e.getMessage(), e); - } - } - - protected void processType(ObjectNode root, ClassInfo type) { - if (hasStringConstructor(type)) { - ArrayNode anyOf = root.putArray("anyOf"); - anyOf.addObject() - .put("type", "string"); - - root = anyOf.addObject(); - } - - root.put("type", "object"); - - boolean allOf = false; - if (implementsInterface(type, HAS_EXPRESSION_CLASS)) { - root.withArray("allOf").addObject().put("$ref", "#/items/definitions/expressions"); - allOf = true; - } - if (implementsInterface(type, HAS_DATAFORMAT_CLASS)) { - root.withArray("allOf").addObject().put("$ref", "#/items/definitions/dataformats"); - allOf = true; - } - - if (allOf) { - root = root.withArray("allOf").addObject(); - } - - processFields(root, type); - processMethods(root, type); - } - - protected void processFields(ObjectNode root, ClassInfo type) { - for (FieldInfo fi : IndexerSupport.fields(view.get(), type)) { - if (fi.hasAnnotation(XML_TRANSIENT_CLASS) - || fi.hasAnnotation(JSON_IGNORE_CLASS)) { - continue; - } - if (!fi.hasAnnotation(XML_VALUE_ANNOTATION_CLASS) - && !fi.hasAnnotation(XML_ATTRIBUTE_ANNOTATION_CLASS) - && !fi.hasAnnotation(JSON_PROPERTY_CLASS)) { - continue; - } - - String fieldName = firstPresent( - annotationValue(fi, XML_VALUE_ANNOTATION_CLASS, "name") - .map(AnnotationValue::asString) - .filter(value -> !"##default".equals(value)), - annotationValue(fi, XML_ATTRIBUTE_ANNOTATION_CLASS, "name") - .map(AnnotationValue::asString) - .filter(value -> !"##default".equals(value)), - annotationValue(fi, JSON_PROPERTY_CLASS, "value") - .map(AnnotationValue::asString) - .filter(value -> !"##default".equals(value)) - ).orElseGet(fi::name); - - String propertyName = StringHelper.camelCaseToDash(fieldName); - ObjectNode property = root.with("properties").with(propertyName); - - setJsonSchemaType(property, fi.type()); - - annotationValue(fi, METADATA_ANNOTATION, "defaultValue") - .map(AnnotationValue::asString) - .filter(ObjectHelper::isEmpty) - .ifPresent(val -> property.put("default", val)); - annotationValue(fi, METADATA_ANNOTATION, "description") - .map(AnnotationValue::asString) - .filter(ObjectHelper::isEmpty) - .ifPresent(val -> property.put("description", val)); - annotationValue(fi, METADATA_ANNOTATION, "enums") - .map(AnnotationValue::asString) - .ifPresent(val -> setEnum(property, "enum", val)); - - if (isRequired(fi)) { - root.withArray("required").add(propertyName); - } - } - } - - protected void processMethods(ObjectNode root, ClassInfo type) { - for (MethodInfo mi : IndexerSupport.methods(view.get(), type)) { - if (mi.hasAnnotation(JSON_IGNORE_CLASS)) { - continue; - } - if (!mi.hasAnnotation(JSON_PROPERTY_CLASS) && !mi.hasAnnotation(JSON_ALIAS_CLASS)) { - continue; - } - if (mi.parameters().size() != 1) { - continue; - } - - String methodName = firstPresent( - annotationValue(mi, JSON_ALIAS_CLASS, "value") - .map(AnnotationValue::asStringArray) - .filter(values -> values.length > 0) - .map(values -> values[0]) - .filter(ObjectHelper::isNotEmpty), - annotationValue(mi, JSON_PROPERTY_CLASS, "value") - .map(AnnotationValue::asString) - .filter(ObjectHelper::isNotEmpty) - ).orElseGet(mi::name); - - if (methodName.startsWith("set")) { - methodName = StringHelper.after(methodName, "set"); - } - - String propertyName = StringHelper.camelCaseToDash(methodName); - ObjectNode property = root.with("properties").with(propertyName); - - Type param = mi.parameters().get(0); - - // register types for classes - if (param.kind() == Type.Kind.CLASS) { - ClassInfo ci = view.get().getClassByName(param.name()); - if (ci != null && !definitions.has(ci.name().toString())) { - processType(definitions.putObject(ci.name().toString()), ci); - } - } - - setJsonSchemaType(property, param); - - annotationValue(mi, METADATA_ANNOTATION, "defaultValue") - .map(AnnotationValue::asString) - .filter(ObjectHelper::isEmpty) - .ifPresent(val -> property.put("default", val)); - annotationValue(mi, METADATA_ANNOTATION, "description") - .map(AnnotationValue::asString) - .filter(ObjectHelper::isEmpty) - .ifPresent(val -> property.put("description", val)); - annotationValue(mi, METADATA_ANNOTATION, "enums") - .map(AnnotationValue::asString) - .ifPresent(val -> setEnum(property, "enum", val)); - - if (isRequired(mi)) { - root.withArray("required").add(propertyName); - } - } - } - - // ******************************************* - // - // Helpers - // - // ******************************************* - - protected boolean isRequired(FieldInfo fi) { - return firstPresent( - annotationValue(fi, METADATA_ANNOTATION, "required") - .map(AnnotationValue::asBoolean), - annotationValue(fi, JSON_PROPERTY_CLASS, "required") - .map(AnnotationValue::asBoolean), - annotationValue(fi, XML_VALUE_ANNOTATION_CLASS, "required") - .map(AnnotationValue::asBoolean) - ).orElse(false); - } - - protected boolean isRequired(MethodInfo mi) { - return firstPresent( - annotationValue(mi, METADATA_ANNOTATION, "required") - .map(AnnotationValue::asBoolean), - annotationValue(mi, JSON_PROPERTY_CLASS, "required") - .map(AnnotationValue::asBoolean) - ).orElse(false); - } - - protected static void setEnum(ObjectNode root, String name, String enumValues) { - ObjectHelper.notNull(root, "root"); - ObjectHelper.notNull(name, "name"); - - if (ObjectHelper.isEmpty(enumValues)) { - return; - } - - ArrayNode array = root.putArray(name); - for (String enumValue: enumValues.split(",")) { - array.add(enumValue); - } - } - - protected static boolean hasStringConstructor(ClassInfo type) { - DotName javaLangString = DotName.createSimple("java.lang.String"); - - for (MethodInfo mi: type.methods()) { - if (!"<init>".equals(mi.name())) { - continue; - } - if (mi.parameters().size() != 1) { - continue; - } - if (mi.parameters().get(0).name().equals(javaLangString)) { - return true; - } - } - - return false; - } - - protected static boolean implementsInterface(ClassInfo type, DotName interfaceName) { - return type.interfaceNames().stream().anyMatch(i -> i.equals(interfaceName)); - } - - protected void setJsonSchemaType(ObjectNode node, Type type) { - if (type.kind() == Type.Kind.PARAMETERIZED_TYPE) { - ParameterizedType parameterized = type.asParameterizedType(); - - if (parameterized.arguments().size() == 1) { - final Type parametrizedType = parameterized.arguments().get(0); - final ClassInfo parametrizedTypeInfo = view.get().getClassByName(parametrizedType.name()); - - if (parameterized.name().equals(LIST_CLASS) && parametrizedTypeInfo != null) { - if (parametrizedTypeInfo.name().equals(STEP_CLASS)) { - node.put("type", "array"); - node.with("items").put("$ref", "#/items/definitions/step"); - return; - } - if (parametrizedTypeInfo.classAnnotation(YAML_NODE_DEFINITION_ANNOTATION) != null) { - node.put("type", "array"); - node.with("items").put("$ref", "#/items/definitions/" + parametrizedTypeInfo.name().toString()); - return; - } - } - } - } - - final ClassInfo typeClass = view.get().getClassByName(type.name()); - if (typeClass != null && typeClass.classAnnotation(YAML_NODE_DEFINITION_ANNOTATION) != null) { - node.put("$ref", "#/items/definitions/" + type.name().toString()); - return; - } - - final String javaType = type.name().toString(); - switch (javaType) { - /* - * <tr><th scope="row"> boolean <td style="text-align:center"> Z - * <tr><th scope="row"> byte <td style="text-align:center"> B - * <tr><th scope="row"> char <td style="text-align:center"> C - * <tr><th scope="row"> class or interface <td style="text-align:center"> L<i>classname</i>; - * <tr><th scope="row"> double <td style="text-align:center"> D - * <tr><th scope="row"> float <td style="text-align:center"> F - * <tr><th scope="row"> int <td style="text-align:center"> I - * <tr><th scope="row"> long <td style="text-align:center"> J - * <tr><th scope="row"> short <td style="text-align:center"> S - */ - case "java.lang.Class": - node.put("type", "string"); - break; - case "[B": - node.put("type", "string"); - node.put("format", "binary"); - break; - case "[Ljava.lang.Class;": - node.put("type", "array"); - node.with("items").put("type", "string"); - break; - case "boolean": - node.put("type", "boolean"); - break; - case "char": - node.put("type", "string"); - break; - case "int": - case "float": - case "long": - case "double": - node.put("type", "number"); - break; - default: - if (definitions.has(javaType)) { - node.put("$ref", "#/items/definitions/" + javaType); - } else { - try { - Class<?> clazz = MavenSupport.getClassLoader(project).loadClass(javaType); - - if (clazz.isEnum()) { - ArrayNode array = node.putArray("enum"); - for (Object t : clazz.getEnumConstants()) { - array.add(((Enum) t).name()); - } - } else if (CharSequence.class.isAssignableFrom(clazz)) { - node.put("type", "string"); - } else if (Boolean.class.isAssignableFrom(clazz)) { - node.put("type", "boolean"); - } else if (Number.class.isAssignableFrom(clazz)) { - node.put("type", "number"); - } else if (Collection.class.isAssignableFrom(clazz)) { - node.put("type", "array"); - node.with("items").put("type", "string"); - } else if (Map.class.isAssignableFrom(clazz)) { - node.put("type", "object"); - } else { - throw new IllegalStateException("Unknown java_type: " + javaType + " on node: " + node); - } - } catch (ClassNotFoundException e) { - throw new IllegalStateException("Unknown java_type: " + javaType + " on node: " + node, e); - } - } - } - } - - - @SafeVarargs - protected final <T> Optional<T> firstPresent(Optional<T>... optionals) { - for (Optional<T> optional: optionals) { - if (optional.isPresent()) { - return optional; - } - } - - return Optional.empty(); - - } -} diff --git a/support/camel-k-maven-plugin/src/main/java/org/apache/camel/k/tooling/maven/GenerateYamlSupport.java b/support/camel-k-maven-plugin/src/main/java/org/apache/camel/k/tooling/maven/GenerateYamlSupport.java deleted file mode 100644 index 3dc12eab..00000000 --- a/support/camel-k-maven-plugin/src/main/java/org/apache/camel/k/tooling/maven/GenerateYamlSupport.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.camel.k.tooling.maven; - - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; -import java.util.function.Supplier; -import java.util.stream.Stream; - -import org.apache.camel.k.tooling.maven.support.IndexerSupport; -import org.apache.camel.k.tooling.maven.support.MavenSupport; -import org.apache.camel.util.function.Suppliers; -import org.apache.maven.plugin.AbstractMojo; -import org.apache.maven.plugins.annotations.Parameter; -import org.apache.maven.project.MavenProject; -import org.jboss.jandex.AnnotationInstance; -import org.jboss.jandex.AnnotationTarget; -import org.jboss.jandex.AnnotationValue; -import org.jboss.jandex.ClassInfo; -import org.jboss.jandex.DotName; -import org.jboss.jandex.FieldInfo; -import org.jboss.jandex.IndexView; -import org.jboss.jandex.MethodInfo; - -public abstract class GenerateYamlSupport extends AbstractMojo { - - public static final DotName LIST_CLASS = - DotName.createSimple("java.util.List"); - - public static final DotName XML_ROOT_ELEMENT_ANNOTATION_CLASS = - DotName.createSimple("javax.xml.bind.annotation.XmlRootElement"); - public static final DotName XML_ATTRIBUTE_ANNOTATION_CLASS = - DotName.createSimple("javax.xml.bind.annotation.XmlAttribute"); - public static final DotName XML_VALUE_ANNOTATION_CLASS = - DotName.createSimple("javax.xml.bind.annotation.XmlValue"); - public static final DotName XML_TRANSIENT_CLASS = - DotName.createSimple("javax.xml.bind.annotation.XmlTransient"); - - public static final DotName JSON_PROPERTY_CLASS = - DotName.createSimple("com.fasterxml.jackson.annotation.JsonProperty"); - public static final DotName JSON_IGNORE_CLASS = - DotName.createSimple("com.fasterxml.jackson.annotation.JsonIgnore"); - public static final DotName JSON_ALIAS_CLASS = - DotName.createSimple("com.fasterxml.jackson.annotation.JsonAlias"); - - public static final DotName METADATA_ANNOTATION = - DotName.createSimple("org.apache.camel.spi.Metadata"); - public static final DotName EXPRESSION_DEFINITION_CLASS = - DotName.createSimple("org.apache.camel.model.language.ExpressionDefinition"); - public static final DotName DATAFORMAT_DEFINITION_CLASS = - DotName.createSimple("org.apache.camel.model.DataFormatDefinition"); - public static final DotName ERROR_HANDLER_CLASS = - DotName.createSimple("org.apache.camel.builder.ErrorHandlerBuilder"); - - public static final DotName YAML_NODE_DEFINITION_ANNOTATION = - DotName.createSimple("org.apache.camel.k.annotation.yaml.YAMLNodeDefinition"); - public static final DotName YAML_STEP_PARSER_ANNOTATION = - DotName.createSimple("org.apache.camel.k.annotation.yaml.YAMLStepParser"); - public static final DotName YAML_MIXIN_ANNOTATION = - DotName.createSimple("org.apache.camel.k.annotation.yaml.YAMLMixIn"); - public static final DotName JSON_SCHEMA_IGNORE_ANNOTATION = - DotName.createSimple("org.apache.camel.k.annotation.yaml.JsonSchemaIgnore"); - public static final DotName LOAD_BALANCE_DEFINITION_CLASS = - DotName.createSimple("org.apache.camel.model.LoadBalancerDefinition"); - public static final DotName START_STEP_PARSER_CLASS = - DotName.createSimple("org.apache.camel.k.loader.yaml.spi.StartStepParser"); - public static final DotName PROCESSOR_STEP_PARSER_CLASS = - DotName.createSimple("org.apache.camel.k.loader.yaml.spi.ProcessorStepParser"); - public static final DotName HAS_EXPRESSION_CLASS = - DotName.createSimple("org.apache.camel.k.loader.yaml.parser.HasExpression"); - public static final DotName HAS_DATAFORMAT_CLASS = - DotName.createSimple("org.apache.camel.k.loader.yaml.parser.HasDataFormat"); - public static final DotName HAS_ENDPOINT_CONSUMER_CLASS = - DotName.createSimple("org.apache.camel.k.loader.yaml.parser.HasEndpointConsumer"); - public static final DotName HAS_ENDPOINT_PRODUCER_CLASS = - DotName.createSimple("org.apache.camel.k.loader.yaml.parser.HasEndpointProducer"); - public static final DotName HAS_URI_PRODUCER_CLASS = - DotName.createSimple("org.apache.camel.k.loader.yaml.parser.HasUri"); - public static final DotName STEP_CLASS = - DotName.createSimple("org.apache.camel.k.loader.yaml.model.Step"); - - - @Parameter(defaultValue = "${project}", readonly = true, required = true) - protected MavenProject project; - - protected final Supplier<IndexView> view; - - GenerateYamlSupport() { - this.view = Suppliers.memorize(() -> IndexerSupport.get(project)); - } - - protected Map<String, ClassInfo> definitions(DotName type) { - Map<String, ClassInfo> definitions = new HashMap<>(); - - for (ClassInfo ci: view.get().getAllKnownSubclasses(type)) { - AnnotationInstance instance = ci.classAnnotation(XML_ROOT_ELEMENT_ANNOTATION_CLASS); - if (instance != null) { - AnnotationValue name = instance.value("name"); - if (name != null) { - definitions.put(name.asString(), ci); - } - } - } - - return Collections.unmodifiableMap(definitions); - } - - protected Stream<ClassInfo> implementors(DotName type) { - return view.get().getAllKnownImplementors(type).stream(); - } - - protected Stream<ClassInfo> annotated(DotName type) { - return view.get().getAnnotations(type).stream() - .map(AnnotationInstance::target) - .filter(t -> t.kind() == AnnotationTarget.Kind.CLASS) - .map(AnnotationTarget::asClass); - } - - protected Optional<AnnotationValue> annotationValue(AnnotationInstance instance, String name) { - return instance != null - ? Optional.ofNullable(instance.value(name)) - : Optional.empty(); - } - - protected Optional<AnnotationValue> annotationValue(ClassInfo target, DotName annotationName, String name) { - return annotationValue( - target.classAnnotation(annotationName), - name - ); - } - - protected Optional<AnnotationValue> annotationValue(FieldInfo target, DotName annotationName, String name) { - return annotationValue( - target.annotation(annotationName), - name - ); - } - - - protected Optional<AnnotationValue> annotationValue(MethodInfo target, DotName annotationName, String name) { - return annotationValue( - target.annotation(annotationName), - name - ); - } - - - protected Class<?> loadClass(ClassInfo ci) { - return loadClass(ci.name().toString()); - } - - protected Class<?> loadClass(String className) { - try { - return MavenSupport.getClassLoader(project).loadClass(className); - } catch (ClassNotFoundException e) { - throw new RuntimeException(e); - } - } -} diff --git a/support/camel-k-maven-plugin/src/main/java/org/apache/camel/k/tooling/maven/support/IndexerSupport.java b/support/camel-k-maven-plugin/src/main/java/org/apache/camel/k/tooling/maven/support/IndexerSupport.java deleted file mode 100644 index 455c63c4..00000000 --- a/support/camel-k-maven-plugin/src/main/java/org/apache/camel/k/tooling/maven/support/IndexerSupport.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.camel.k.tooling.maven.support; - -import java.io.InputStream; -import java.net.URL; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.function.Predicate; - -import org.apache.maven.project.MavenProject; -import org.jboss.jandex.ClassInfo; -import org.jboss.jandex.CompositeIndex; -import org.jboss.jandex.FieldInfo; -import org.jboss.jandex.IndexReader; -import org.jboss.jandex.IndexView; -import org.jboss.jandex.MethodInfo; -import org.jboss.jandex.Type; - -public final class IndexerSupport { - private IndexerSupport() { - } - - public static IndexView get(MavenProject project) { - try { - ClassLoader classLoader = MavenSupport.getClassLoader(project); - Enumeration<URL> elements = classLoader.getResources("META-INF/jandex.idx"); - List<IndexView> allIndex = new ArrayList<>(); - Set<URL> locations = new HashSet<>(); - - while (elements.hasMoreElements()) { - URL url = elements.nextElement(); - if (locations.add(url)) { - try (InputStream is = url.openStream()) { - allIndex.add(new IndexReader(is).read()); - } - } - } - - return CompositeIndex.create(allIndex); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - public static List<FieldInfo> fields(IndexView view, ClassInfo type) { - return fields(view, type, fi -> true); - } - - public static List<FieldInfo> fields(IndexView view, ClassInfo type, Predicate<FieldInfo> filter) { - List<FieldInfo> answer = new ArrayList<>(); - - for (ClassInfo current = type; current != null;) { - for (FieldInfo fieldInfo: current.fields()) { - if (filter.test(fieldInfo)) { - answer.add(fieldInfo); - } - } - - Type superType = current.superClassType(); - if (superType == null) { - break; - } - - current = view.getClassByName(superType.name()); - } - - return answer; - } - - - - public static List<MethodInfo> methods(IndexView view, ClassInfo type) { - return methods(view, type, mi -> true); - } - - public static List<MethodInfo> methods(IndexView view, ClassInfo type, Predicate<MethodInfo> filter) { - List<MethodInfo> answer = new ArrayList<>(); - - for (ClassInfo current = type; current != null;) { - for (MethodInfo methodInfo: current.methods()) { - if (filter.test(methodInfo)) { - answer.add(methodInfo); - } - } - - Type superType = current.superClassType(); - if (superType == null) { - break; - } - - current = view.getClassByName(superType.name()); - } - - return answer; - } -} diff --git a/support/camel-k-maven-plugin/src/main/java/org/apache/camel/k/tooling/maven/support/MavenSupport.java b/support/camel-k-maven-plugin/src/main/java/org/apache/camel/k/tooling/maven/support/MavenSupport.java index e45b5292..ee6e64c6 100644 --- a/support/camel-k-maven-plugin/src/main/java/org/apache/camel/k/tooling/maven/support/MavenSupport.java +++ b/support/camel-k-maven-plugin/src/main/java/org/apache/camel/k/tooling/maven/support/MavenSupport.java @@ -16,41 +16,17 @@ */ package org.apache.camel.k.tooling.maven.support; -import java.io.File; import java.io.IOException; import java.io.InputStream; -import java.net.URL; -import java.net.URLClassLoader; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; -import java.util.ArrayList; -import java.util.List; import java.util.Properties; import java.util.function.Consumer; -import org.apache.maven.project.MavenProject; - public final class MavenSupport { private MavenSupport() { } - public static ClassLoader getClassLoader(MavenProject project) { - if (project == null) { - return IndexerSupport.class.getClassLoader(); - } - - try { - List<String> elements = new ArrayList<>(project.getCompileClasspathElements()); - URL[] urls = new URL[elements.size()]; - for (int i = 0; i < elements.size(); ++i) { - urls[i] = new File(elements.get(i)).toURI().toURL(); - } - return new URLClassLoader(urls, IndexerSupport.class.getClassLoader()); - } catch (Exception e) { - return IndexerSupport.class.getClassLoader(); - } - } - public static String getVersion(Class<?> clazz, String path) { String version = null; diff --git a/support/camel-k-maven-plugin/src/main/java/org/apache/camel/k/tooling/maven/support/ToolingSupport.java b/support/camel-k-maven-plugin/src/main/java/org/apache/camel/k/tooling/maven/support/ToolingSupport.java deleted file mode 100644 index d7aca34e..00000000 --- a/support/camel-k-maven-plugin/src/main/java/org/apache/camel/k/tooling/maven/support/ToolingSupport.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.camel.k.tooling.maven.support; - -import java.io.File; -import java.io.IOException; -import java.util.Set; -import java.util.TreeSet; -import java.util.stream.Stream; - -public final class ToolingSupport { - private ToolingSupport() { - } - - /** - * Combines the given items assuming they can be also composed - * by comma separated elements. - * - * @param items the items - * @return a stream of individual items - */ - public static Stream<String> combine(String... items) { - Set<String> answer = new TreeSet<>(); - - for (String item: items) { - if (item == null) { - continue; - } - - String[] elements = item.split(","); - for (String element: elements) { - answer.add(element); - } - } - - return answer.stream(); - } - - public static void mkparents(File path) throws IOException { - if (!path.getParentFile().exists() && !path.getParentFile().mkdirs()) { - throw new IOException("Unable to create directory " + path.getParentFile()); - } - } -} diff --git a/support/camel-k-maven-plugin/src/test/java/org/apache/camel/k/tooling/maven/processors/GenerateYamlSupportClassesTest.java b/support/camel-k-maven-plugin/src/test/java/org/apache/camel/k/tooling/maven/processors/GenerateYamlSupportClassesTest.java deleted file mode 100644 index 52bfb261..00000000 --- a/support/camel-k-maven-plugin/src/test/java/org/apache/camel/k/tooling/maven/processors/GenerateYamlSupportClassesTest.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.camel.k.tooling.maven.processors; - -import com.squareup.javapoet.JavaFile; -import com.squareup.javapoet.TypeSpec; -import org.apache.camel.k.tooling.maven.GenerateYamlLoaderSupportClasses; -import org.apache.camel.k.tooling.maven.GenerateYamlParserSupportClasses; -import org.junit.jupiter.api.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -public class GenerateYamlSupportClassesTest { - @Test - public void testGenerateHasDataFormat() { - final TypeSpec spec = new GenerateYamlParserSupportClasses().generateHasDataFormat(); - final JavaFile file = JavaFile.builder("org.apache.camel.k.loader.yaml.parser", spec).build(); - - assertThat(file.packageName).isEqualTo("org.apache.camel.k.loader.yaml.parser"); - assertThat(spec.name).isEqualTo("HasDataFormat"); - assertThat(spec.methodSpecs).isNotEmpty(); - } - - @Test - public void testGenerateHasExpression() { - final TypeSpec spec = new GenerateYamlParserSupportClasses().generateHasExpression(); - final JavaFile file = JavaFile.builder("org.apache.camel.k.loader.yaml.parser", spec).build(); - - assertThat(file.packageName).isEqualTo("org.apache.camel.k.loader.yaml.parser"); - assertThat(spec.name).isEqualTo("HasExpression"); - assertThat(spec.methodSpecs).isNotEmpty(); - } - - @Test - public void testGenerateJacksonModule() { - final TypeSpec spec = new GenerateYamlLoaderSupportClasses().generateJacksonModule(); - final JavaFile file = JavaFile.builder("org.apache.camel.k.loader.yaml", spec).build(); - - assertThat(file.packageName).isEqualTo("org.apache.camel.k.loader.yaml"); - assertThat(spec.name).isEqualTo("YamlModule"); - assertThat(spec.methodSpecs).isNotEmpty(); - } -}