This is an automated email from the ASF dual-hosted git repository. Croway pushed a commit to branch camel-4.18.6-recipes in repository https://gitbox.apache.org/repos/asf/camel-upgrade-recipes.git
commit b014908161834dbb1c5a3235f3de5f48f707826f Author: croway <[email protected]> AuthorDate: Mon Nov 30 11:38:56 2026 +0100 Flag the 4.18.6 changes that cannot be rewritten safely Six changes of Camel 4.18.6, which also ship in 4.22.3 and 4.24.0 (not in 4.22.2 or 4.23.0, checked in the code at the tags), leave nothing a recipe can rewrite without a decision of the user: setting the new option would undo the reason of the change, or the right value depends on the deployment. The recipes add a review comment, starting with the JIRA key, where the affected code is: - CAMEL-27052 camel-jaxb: setting CamelJaxbPartClass / CamelJaxbPartNamespace (allowPartClassFromHeader) - CAMEL-27227 camel-smpp: setting CamelSmppSystemId / CamelSmppPassword (allowSystemIdAndPasswordFromHeaders) - CAMEL-27225 camel-redis: creating or declaring RedisAggregationRepository (storage format) - CAMEL-26587 camel-netty: NettyPayloadHelper.setIn/setOut(Exchange, Object) - CAMEL-27160 camel-core: #class:, #property: or RAW($simple{...}) in the uri of toD, enrich, pollEnrich, wireTap, recipientList, routingSlip and dynamicRouter - CAMEL-26281 camel-whatsapp: a webhook:whatsapp: consumer without webhookSecret or webhookVerification Following RECIPE-CONVENTIONS.md they live in camel418_6, chained by camel418_6.CamelMigrationRecipe, and camel422_3 references them (camel424 gets them through camel422_3). They are built on three generic recipes in camel418_6: FlagHeaderWhenSet (the counterpart of RenameHeaderWhenSet), FlagTypeOrMethodUse and FlagEndpointUri, for the Java, XML and YAML DSLs. A comment already there is not added again, so the 4.18 LTS aggregate can run them on every upgrade. --- .../camel/upgrade/camel418_6/FlagEndpointUri.java | 358 +++++++++++++ .../upgrade/camel418_6/FlagHeaderWhenSet.java | 257 +++++++++ .../upgrade/camel418_6/FlagTypeOrMethodUse.java | 257 +++++++++ .../camel/upgrade/camel418_6/ReviewComment.java | 183 +++++++ .../main/resources/META-INF/rewrite/4.18.6.yaml | 121 +++++ .../main/resources/META-INF/rewrite/4.22.3.yaml | 6 + .../apache/camel/upgrade/CamelUpdate418_6Test.java | 586 +++++++++++++++++++++ release_notes.adoc | 32 +- 8 files changed, 1798 insertions(+), 2 deletions(-) diff --git a/camel-upgrade-recipes/src/main/java/org/apache/camel/upgrade/camel418_6/FlagEndpointUri.java b/camel-upgrade-recipes/src/main/java/org/apache/camel/upgrade/camel418_6/FlagEndpointUri.java new file mode 100644 index 0000000..40649eb --- /dev/null +++ b/camel-upgrade-recipes/src/main/java/org/apache/camel/upgrade/camel418_6/FlagEndpointUri.java @@ -0,0 +1,358 @@ +/* + * 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.upgrade.camel418_6; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.regex.Pattern; + +import org.apache.camel.upgrade.AbstractCamelJavaVisitor; +import org.apache.camel.upgrade.AbstractCamelXmlVisitor; +import org.apache.camel.upgrade.RecipesUtil; +import org.openrewrite.Cursor; +import org.openrewrite.ExecutionContext; +import org.openrewrite.Option; +import org.openrewrite.Preconditions; +import org.openrewrite.Recipe; +import org.openrewrite.TreeVisitor; +import org.openrewrite.java.JavaIsoVisitor; +import org.openrewrite.java.tree.J; +import org.openrewrite.java.tree.JContainer; +import org.openrewrite.java.tree.JRightPadded; +import org.openrewrite.java.tree.JavaType; +import org.openrewrite.xml.tree.Xml; +import org.openrewrite.yaml.YamlIsoVisitor; +import org.openrewrite.yaml.tree.Yaml; + +/** + * Adds a review comment where an endpoint uri written in one of the given EIPs matches a pattern, unless another + * pattern is found in the same EIP: for example a {@code #class:} option value in a {@code toD} uri, or a + * {@code webhook:whatsapp:} consumer without {@code webhookSecret}. + * <p> + * The uri is the string literal passed to the EIP method of the Java DSL, directly, through {@code simple("...")} or + * {@code constant("...")}, or to {@code uri(...)} called on it ({@code toD().uri("...")}); the {@code uri} attribute + * or the {@code <simple>} / {@code <constant>} expression of the EIP element of the XML DSL; the {@code uri}, + * {@code simple}, {@code constant} or {@code expression} value, the {@code parameters} (as {@code name=value}), or the + * value of the shorthand form ({@code toD: "..."}) under the EIP entry of the YAML DSL. The exclusion is looked for in + * the same places. Only literal text is checked: a uri built by code or taken from a property is not. + * <p> + * Limits: OpenRewrite parses a YAML flow mapping ({@code {uri: x, parameters: {...}}}) as one scalar, which is checked + * as a whole; a YAML entry on the first line of a file has no line to put the comment on; and in an XML document the + * EIP elements are matched by their local name. + */ +public class FlagEndpointUri extends Recipe { + + @Option(displayName = "EIPs", description = "Names of the EIPs whose uri is checked, as in the Java, XML and YAML DSLs.", + example = "[toD, enrich, pollEnrich, wireTap]") + List<String> eips; + + @Option(displayName = "Uri pattern", description = "Regular expression found in the uri to flag.", + example = "[?&][^=&]+=#(class|property):") + String uriPattern; + + @Option(displayName = "Unless pattern", + description = "Regular expression that, found anywhere in the same EIP, means the uri is not flagged.", + example = "webhookSecret|webhookVerification", required = false) + String unlessPattern; + + @Option(displayName = "Comment", + description = "The review comment. It starts with the JIRA key, which identifies a comment already added.", + example = " CAMEL-27160: review the option values of this dynamic endpoint.") + String comment; + + public FlagEndpointUri() { + } + + public void setEips(List<String> eips) { + this.eips = eips; + } + + public void setUriPattern(String uriPattern) { + this.uriPattern = uriPattern; + } + + public void setUnlessPattern(String unlessPattern) { + this.unlessPattern = unlessPattern; + } + + public void setComment(String comment) { + this.comment = comment; + } + + @Override + public String getDisplayName() { + return "Flag an endpoint uri of an EIP"; + } + + @Override + public String getDescription() { + return "Adds a review comment where an endpoint uri written in one of the given EIPs of the Java, XML or YAML " + + "DSL matches a pattern, unless another pattern is found in the same EIP."; + } + + @Override + public List<Recipe> getRecipeList() { + return Arrays.asList(new JavaRecipe(this), new XmlRecipe(this), new YamlRecipe(this)); + } + + // the keys holding a uri, and the keys of the mappings that may sit between them and the EIP + private static final List<String> URI_KEYS = List.of("uri", "simple", "constant", "expression"); + private static final List<String> EXPRESSION_KEYS = List.of("simple", "constant", "expression"); + + boolean matchesUri(String value) { + return value != null && Pattern.compile(uriPattern).matcher(value).find(); + } + + boolean matchesUnless(String value) { + return unlessPattern != null && value != null && Pattern.compile(unlessPattern).matcher(value).find(); + } + + private abstract static class Part extends Recipe { + final FlagEndpointUri options; + + Part(FlagEndpointUri options) { + this.options = options; + } + + @Override + public String getDescription() { + return options.getDescription(); + } + } + + private static final class JavaRecipe extends Part { + JavaRecipe(FlagEndpointUri options) { + super(options); + } + + @Override + public String getDisplayName() { + return "Flag an endpoint uri of an EIP in Java"; + } + + @Override + public TreeVisitor<?, ExecutionContext> getVisitor() { + return RecipesUtil.newVisitor(new AbstractCamelJavaVisitor() { + @Override + protected J.Literal doVisitLiteral(J.Literal literal, ExecutionContext ctx) { + J.Literal l = super.doVisitLiteral(literal, ctx); + if (!(l.getValue() instanceof String value) || !options.matchesUri(value)) { + return l; + } + J.MethodInvocation eip = enclosingEip(); + if (eip == null || (options.unlessPattern != null && literals(eip).stream().anyMatch(options::matchesUnless))) { + return l; + } + return ReviewComment.java(l, options.comment); + } + + /** + * The EIP call the literal is the uri of: the literal is (in) the first argument of the EIP method, of + * simple() or constant() passed to it, or of uri() called on it. A literal anywhere else, such as in a + * lambda, an anonymous class, another call passed to the EIP (an aggregation strategy) or a later + * argument (the variable names of toD), is not its uri. + */ + private J.MethodInvocation enclosingEip() { + Object child = null; + Object grandChild = null; + boolean inExpression = false; + for (Cursor c = getCursor().getParent(); c != null; c = c.getParent()) { + Object value = c.getValue(); + if (value instanceof J.Lambda || value instanceof J.Block || value instanceof J.NewClass + || value instanceof J.MemberReference) { + return null; + } + if (value instanceof J.MethodInvocation mi) { + if (!(child instanceof JContainer) || !(grandChild instanceof JRightPadded<?> argument) + || mi.getArguments().isEmpty() || argument.getElement() != mi.getArguments().get(0)) { + return null; + } + if (isEip(mi)) { + return mi; + } + if ("uri".equals(mi.getSimpleName()) && mi.getSelect() instanceof J.MethodInvocation eip + && isEip(eip)) { + return eip; + } + if (inExpression || !("simple".equals(mi.getSimpleName()) || "constant".equals(mi.getSimpleName()))) { + return null; + } + inExpression = true; + } + grandChild = child; + child = value; + } + return null; + } + + /** An EIP of the Camel DSL: the name matches, and the method is Camel's when the call has a type. */ + private boolean isEip(J.MethodInvocation mi) { + if (!options.eips.contains(mi.getSimpleName())) { + return false; + } + JavaType.Method type = mi.getMethodType(); + return type == null || type.getDeclaringType().getFullyQualifiedName().startsWith("org.apache.camel."); + } + + private List<String> literals(J.MethodInvocation eip) { + List<String> found = new ArrayList<>(); + JavaIsoVisitor<List<String>> collector = new JavaIsoVisitor<>() { + @Override + public J.Literal visitLiteral(J.Literal literal, List<String> acc) { + if (literal.getValue() instanceof String value) { + acc.add(value); + } + return literal; + } + }; + eip.getArguments().forEach(arg -> collector.visit(arg, found)); + return found; + } + }); + } + } + + private static final class XmlRecipe extends Part { + XmlRecipe(FlagEndpointUri options) { + super(options); + } + + @Override + public String getDisplayName() { + return "Flag an endpoint uri of an EIP in the XML DSL"; + } + + @Override + public TreeVisitor<?, ExecutionContext> getVisitor() { + return Preconditions.check(RecipesUtil.camelXmlDslPrecondition(), new AbstractCamelXmlVisitor() { + @Override + public Xml.Tag doVisitTag(Xml.Tag tag, ExecutionContext ctx) { + Xml.Tag t = super.doVisitTag(tag, ctx); + return ReviewComment.xmlChildren(t, this::isFlagged, options.comment); + } + + private boolean isFlagged(Xml.Tag eip) { + if (!options.eips.contains(ReviewComment.localName(eip))) { + return false; + } + List<String> values = new ArrayList<>(); + eip.getAttributes().stream().filter(attr -> "uri".equals(attr.getKeyAsString())) + .forEach(attr -> values.add(attr.getValueAsString())); + // the expression of the EIP, such as <simple>...</simple> + for (Xml.Tag child : eip.getChildren()) { + String name = ReviewComment.localName(child); + if (child.getChildren().isEmpty() && ("simple".equals(name) || "constant".equals(name))) { + child.getValue().ifPresent(values::add); + } + } + return values.stream().anyMatch(options::matchesUri) && values.stream().noneMatch(options::matchesUnless); + } + }); + } + } + + private static final class YamlRecipe extends Part { + YamlRecipe(FlagEndpointUri options) { + super(options); + } + + @Override + public String getDisplayName() { + return "Flag an endpoint uri of an EIP in the YAML DSL"; + } + + @Override + public TreeVisitor<?, ExecutionContext> getVisitor() { + return Preconditions.check(RecipesUtil.camelYamlDslPrecondition(), new ReviewComment.YamlVisitor(options.comment) { + @Override + public Yaml.Mapping.Entry doVisitMappingEntry(Yaml.Mapping.Entry entry, ExecutionContext ctx) { + Yaml.Mapping.Entry e = super.doVisitMappingEntry(entry, ctx); + if (!(e.getValue() instanceof Yaml.Scalar scalar)) { + return e; + } + String key = e.getKey().getValue(); + Yaml.Mapping.Entry eip; + String uri; + if (options.eips.contains(key)) { + // the shorthand form: toD: "..." + eip = e; + uri = scalar.getValue(); + } else if (URI_KEYS.contains(key)) { + eip = enclosingEip(false); + uri = scalar.getValue(); + } else { + eip = enclosingEip(true); + uri = key + "=" + scalar.getValue(); + } + if (eip == null || !options.matchesUri(uri) || uriValues(eip).stream().anyMatch(options::matchesUnless)) { + return e; + } + return flag(e); + } + + /** + * The EIP entry the current entry belongs to: the uri entries are directly under it (or under its + * expression), a parameter is in its parameters. + */ + private Yaml.Mapping.Entry enclosingEip(boolean parameter) { + Cursor c = getCursor().getParent(); + boolean inParameters = false; + for (; c != null; c = c.getParent()) { + if (c.getValue() instanceof Yaml.Mapping.Entry parent) { + String key = parent.getKey().getValue(); + if (options.eips.contains(key)) { + return !parameter || inParameters ? parent : null; + } + if (parameter && !inParameters && "parameters".equals(key)) { + inParameters = true; + } else if (parameter || !EXPRESSION_KEYS.contains(key)) { + return null; + } + } + } + return null; + } + + /** The uri values and parameters of the EIP, not the steps or other options under it. */ + private List<String> uriValues(Yaml.Mapping.Entry eip) { + List<String> found = new ArrayList<>(); + new YamlIsoVisitor<List<String>>() { + @Override + public Yaml.Mapping.Entry visitMappingEntry(Yaml.Mapping.Entry entry, List<String> acc) { + String key = entry.getKey().getValue(); + if (entry.getValue() instanceof Yaml.Scalar value) { + if (entry == eip || URI_KEYS.contains(key)) { + acc.add(value.getValue()); + } else if (getCursor().getParentOrThrow(2).getValue() instanceof Yaml.Mapping.Entry parent + && "parameters".equals(parent.getKey().getValue())) { + acc.add(key + "=" + value.getValue()); + } + return entry; + } + if (entry != eip && !"parameters".equals(key) && !EXPRESSION_KEYS.contains(key)) { + return entry; + } + return super.visitMappingEntry(entry, acc); + } + }.visit(eip, found, getCursor().getParentOrThrow()); + return found; + } + }); + } + } +} diff --git a/camel-upgrade-recipes/src/main/java/org/apache/camel/upgrade/camel418_6/FlagHeaderWhenSet.java b/camel-upgrade-recipes/src/main/java/org/apache/camel/upgrade/camel418_6/FlagHeaderWhenSet.java new file mode 100644 index 0000000..1c38a92 --- /dev/null +++ b/camel-upgrade-recipes/src/main/java/org/apache/camel/upgrade/camel418_6/FlagHeaderWhenSet.java @@ -0,0 +1,257 @@ +/* + * 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.upgrade.camel418_6; + +import java.util.Arrays; +import java.util.List; +import java.util.regex.Pattern; + +import org.apache.camel.upgrade.AbstractCamelJavaVisitor; +import org.apache.camel.upgrade.AbstractCamelXmlVisitor; +import org.apache.camel.upgrade.RecipesUtil; +import org.openrewrite.Cursor; +import org.openrewrite.ExecutionContext; +import org.openrewrite.Option; +import org.openrewrite.Preconditions; +import org.openrewrite.Recipe; +import org.openrewrite.TreeVisitor; +import org.openrewrite.internal.ListUtils; +import org.openrewrite.java.MethodMatcher; +import org.openrewrite.java.tree.Expression; +import org.openrewrite.java.tree.J; +import org.openrewrite.java.tree.JavaType; +import org.openrewrite.xml.tree.Xml; +import org.openrewrite.yaml.tree.Yaml; + +/** + * Adds a review comment where a route sets one of the given headers: {@code setHeader} in the Java DSL and on a + * {@code Message}, {@code <setHeader name="...">} in the XML DSL and {@code setHeader: name:} in the YAML DSL. Reads + * of the headers are left alone. + * <p> + * For a header that a component now ignores unless an option allows it, where adding the option would undo the + * reason of the change, for example the JAXB part class header ({@code allowPartClassFromHeader}) or the SMPP + * credential headers ({@code allowSystemIdAndPasswordFromHeaders}). In the Java DSL the header may be a string + * literal or a constant of {@code constantClass}; a statically imported constant is not recognised. + */ +public class FlagHeaderWhenSet extends Recipe { + + @Option(displayName = "Header names", description = "The header names to flag where a route sets them.", + example = "[CamelJaxbPartClass, CamelJaxbPartNamespace]") + List<String> headerNames; + + @Option(displayName = "Constant class", description = "Fully qualified class of the header constants.", + example = "org.apache.camel.converter.jaxb.JaxbConstants", required = false) + String constantClass; + + @Option(displayName = "Constant names", description = "The constants of constantClass holding the header names.", + example = "[JAXB_PART_CLASS, JAXB_PART_NAMESPACE]", required = false) + List<String> constantNames; + + @Option(displayName = "Comment", + description = "The review comment. It starts with the JIRA key, which identifies a comment already added.", + example = " CAMEL-27052: the JAXB data format ignores this header unless allowPartClassFromHeader=true.") + String comment; + + public FlagHeaderWhenSet() { + } + + public void setHeaderNames(List<String> headerNames) { + this.headerNames = headerNames; + } + + public void setConstantClass(String constantClass) { + this.constantClass = constantClass; + } + + public void setConstantNames(List<String> constantNames) { + this.constantNames = constantNames; + } + + public void setComment(String comment) { + this.comment = comment; + } + + @Override + public String getDisplayName() { + return "Flag a Camel header where it is set"; + } + + @Override + public String getDescription() { + return "Adds a review comment where setHeader of the Java, XML and YAML DSLs or Message.setHeader sets one of " + + "the given headers."; + } + + @Override + public List<Recipe> getRecipeList() { + return Arrays.asList(new JavaRecipe(this), new XmlRecipe(this), new YamlRecipe(this)); + } + + private abstract static class Part extends Recipe { + final FlagHeaderWhenSet options; + + Part(FlagHeaderWhenSet options) { + this.options = options; + } + + @Override + public String getDescription() { + return options.getDescription(); + } + } + + private static final class JavaRecipe extends Part { + JavaRecipe(FlagHeaderWhenSet options) { + super(options); + } + + @Override + public String getDisplayName() { + return "Flag a header where it is set in Java"; + } + + @Override + public TreeVisitor<?, ExecutionContext> getVisitor() { + return RecipesUtil.newVisitor(new AbstractCamelJavaVisitor() { + // matchOverrides=true: also DefaultMessage and the other Message implementations + private final MethodMatcher messageSetHeader + = new MethodMatcher("org.apache.camel.Message setHeader(String, Object)", true); + // matchOverrides=true: the DSL method is invoked on ProcessorDefinition subtypes (RouteDefinition, ...) + private final MethodMatcher dslSetHeader + = new MethodMatcher("org.apache.camel.model.ProcessorDefinition setHeader(String, ..)", true); + + @Override + protected J.MethodInvocation doVisitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx) { + J.MethodInvocation mi = super.doVisitMethodInvocation(method, ctx); + if (mi.getArguments().isEmpty() + || !(messageSetHeader.matches(mi) || dslSetHeader.matches(mi) || isUntypedSetHeader(mi))) { + return mi; + } + Expression header = mi.getArguments().get(0); + if (!isFlaggedHeader(header)) { + return mi; + } + Expression flagged = ReviewComment.java(header, options.comment); + return flagged == header ? mi : mi.withArguments(ListUtils.mapFirst(mi.getArguments(), a -> flagged)); + } + + /** + * A setHeader call the parser could not attribute, for example because its first argument is a + * constant of a component that is not on the classpath of the recipe run, which also leaves the + * calls chained after it without a type. Only a comment is added, so matching the name is enough. + */ + private boolean isUntypedSetHeader(J.MethodInvocation mi) { + return mi.getMethodType() == null && "setHeader".equals(mi.getSimpleName()) + && mi.getArguments().size() == 2; + } + + private boolean isFlaggedHeader(Expression arg) { + if (arg instanceof J.Literal literal) { + return literal.getValue() instanceof String value && options.headerNames.contains(value); + } + if (options.constantClass == null || options.constantNames == null + || !(arg instanceof J.FieldAccess fa) || !options.constantNames.contains(fa.getSimpleName())) { + return false; + } + JavaType.Variable field = fa.getName().getFieldType(); + if (field != null && field.getOwner() instanceof JavaType.FullyQualified owner + && !(owner instanceof JavaType.Unknown)) { + return options.constantClass.equals(owner.getFullyQualifiedName()); + } + // the component may not be on the classpath of the recipe run: fall back on the import + return fa.getTarget() instanceof J.Identifier target + && options.constantClass.endsWith("." + target.getSimpleName()) + && ReviewComment.imports(getCursor(), options.constantClass); + } + }); + } + } + + private static final class XmlRecipe extends Part { + XmlRecipe(FlagHeaderWhenSet options) { + super(options); + } + + @Override + public String getDisplayName() { + return "Flag a header where it is set in the XML DSL"; + } + + @Override + public TreeVisitor<?, ExecutionContext> getVisitor() { + return Preconditions.check(RecipesUtil.camelXmlDslPrecondition(), new AbstractCamelXmlVisitor() { + @Override + public Xml.Tag doVisitTag(Xml.Tag tag, ExecutionContext ctx) { + Xml.Tag t = super.doVisitTag(tag, ctx); + return ReviewComment.xmlChildren(t, child -> "setHeader".equals(ReviewComment.localName(child)) + && child.getAttributes().stream().anyMatch(attr -> "name".equals(attr.getKeyAsString()) + && options.headerNames.contains(attr.getValueAsString())), + options.comment); + } + }); + } + } + + private static final class YamlRecipe extends Part { + YamlRecipe(FlagHeaderWhenSet options) { + super(options); + } + + @Override + public String getDisplayName() { + return "Flag a header where it is set in the YAML DSL"; + } + + @Override + public TreeVisitor<?, ExecutionContext> getVisitor() { + return Preconditions.check(RecipesUtil.camelYamlDslPrecondition(), new ReviewComment.YamlVisitor(options.comment) { + @Override + public Yaml.Mapping.Entry doVisitMappingEntry(Yaml.Mapping.Entry entry, ExecutionContext ctx) { + Yaml.Mapping.Entry e = super.doVisitMappingEntry(entry, ctx); + if ("name".equals(e.getKey().getValue()) && e.getValue() instanceof Yaml.Scalar scalar + && options.headerNames.contains(scalar.getValue()) && "setHeader".equals(enclosingKey())) { + return flag(e); + } + // a flow mapping, setHeader: {name: x, constant: y}, is parsed as one scalar + if ("setHeader".equals(e.getKey().getValue()) && e.getValue() instanceof Yaml.Scalar scalar + && options.headerNames.stream().anyMatch(name -> flowMappingNames(scalar.getValue(), name))) { + return flag(e); + } + return e; + } + + private boolean flowMappingNames(String value, String headerName) { + String trimmed = value.trim(); + return trimmed.startsWith("{") && Pattern.compile( + "[{,]\\s*name\\s*:\\s*([\"']?)" + Pattern.quote(headerName) + "\\1\\s*[,}]").matcher(trimmed).find(); + } + + /** Key of the nearest mapping entry enclosing the current one ({@code setHeader} for its name). */ + private String enclosingKey() { + Cursor c = getCursor().getParent(); + while (c != null) { + if (c.getValue() instanceof Yaml.Mapping.Entry parent) { + return parent.getKey().getValue(); + } + c = c.getParent(); + } + return null; + } + }); + } + } +} diff --git a/camel-upgrade-recipes/src/main/java/org/apache/camel/upgrade/camel418_6/FlagTypeOrMethodUse.java b/camel-upgrade-recipes/src/main/java/org/apache/camel/upgrade/camel418_6/FlagTypeOrMethodUse.java new file mode 100644 index 0000000..a5f5d01 --- /dev/null +++ b/camel-upgrade-recipes/src/main/java/org/apache/camel/upgrade/camel418_6/FlagTypeOrMethodUse.java @@ -0,0 +1,257 @@ +/* + * 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.upgrade.camel418_6; + +import java.util.Arrays; +import java.util.List; + +import org.apache.camel.upgrade.AbstractCamelJavaVisitor; +import org.apache.camel.upgrade.AbstractCamelXmlVisitor; +import org.apache.camel.upgrade.RecipesUtil; +import org.openrewrite.ExecutionContext; +import org.openrewrite.Option; +import org.openrewrite.Preconditions; +import org.openrewrite.Recipe; +import org.openrewrite.TreeVisitor; +import org.openrewrite.java.MethodMatcher; +import org.openrewrite.java.tree.Expression; +import org.openrewrite.java.tree.J; +import org.openrewrite.java.tree.JavaType; +import org.openrewrite.java.tree.TypeTree; +import org.openrewrite.java.tree.TypeUtils; +import org.openrewrite.xml.tree.Xml; +import org.openrewrite.yaml.tree.Yaml; + +/** + * Adds a review comment where code creates an instance of a type or calls a method, for a change that depends on + * runtime data or on the deployment, so that no rewrite is safe: for example the storage format of + * {@code RedisAggregationRepository}, or the deprecated two-argument {@code NettyPayloadHelper.setIn/setOut}. + * <p> + * The type is flagged where Java code instantiates it, at a {@code <bean class="...">} (Spring XML) or + * {@code <bean type="...">} (Camel XML DSL), and at a {@code type:} of the Camel YAML DSL {@code beans}. The method + * is flagged where Java code calls it. When the class is not on the classpath of the recipe run, the Java code is + * matched by its simple name and its import. + */ +public class FlagTypeOrMethodUse extends Recipe { + + @Option(displayName = "Fully qualified type name", description = "The type to flag where it is instantiated.", + example = "org.apache.camel.component.redis.processor.aggregate.RedisAggregationRepository", required = false) + String fullyQualifiedTypeName; + + @Option(displayName = "Method pattern", description = "The method to flag where it is called.", + example = "org.apache.camel.component.netty.NettyPayloadHelper setIn(org.apache.camel.Exchange, Object)", + required = false) + String methodPattern; + + @Option(displayName = "Comment", + description = "The review comment. It starts with the JIRA key, which identifies a comment already added.", + example = " CAMEL-27225: review the storage format of this repository.") + String comment; + + public FlagTypeOrMethodUse() { + } + + public void setFullyQualifiedTypeName(String fullyQualifiedTypeName) { + this.fullyQualifiedTypeName = fullyQualifiedTypeName; + } + + public void setMethodPattern(String methodPattern) { + this.methodPattern = methodPattern; + } + + public void setComment(String comment) { + this.comment = comment; + } + + @Override + public String getDisplayName() { + return "Flag the use of a type or a method"; + } + + @Override + public String getDescription() { + return "Adds a review comment where Java code instantiates the type or calls the method, and where an XML or " + + "YAML bean declares the type."; + } + + @Override + public List<Recipe> getRecipeList() { + return fullyQualifiedTypeName == null + ? List.of(new JavaRecipe(this)) + : Arrays.asList(new JavaRecipe(this), new XmlRecipe(this), new YamlRecipe(this)); + } + + boolean isFlaggedTypeName(String value) { + return value != null && (value.equals(fullyQualifiedTypeName) || value.equals("#class:" + fullyQualifiedTypeName)); + } + + private abstract static class Part extends Recipe { + final FlagTypeOrMethodUse options; + + Part(FlagTypeOrMethodUse options) { + this.options = options; + } + + @Override + public String getDescription() { + return options.getDescription(); + } + } + + private static final class JavaRecipe extends Part { + JavaRecipe(FlagTypeOrMethodUse options) { + super(options); + } + + @Override + public String getDisplayName() { + return "Flag the use of a type or a method in Java"; + } + + @Override + public TreeVisitor<?, ExecutionContext> getVisitor() { + return new AbstractCamelJavaVisitor() { + private final MethodMatcher method = options.methodPattern == null + ? null : new MethodMatcher(options.methodPattern); + + @Override + protected J.NewClass doVisitNewClass(J.NewClass newClass, ExecutionContext ctx) { + J.NewClass nc = super.doVisitNewClass(newClass, ctx); + if (options.fullyQualifiedTypeName != null && isFlaggedType(nc)) { + return ReviewComment.java(nc, options.comment); + } + return nc; + } + + @Override + protected J.MethodInvocation doVisitMethodInvocation(J.MethodInvocation invocation, ExecutionContext ctx) { + J.MethodInvocation mi = super.doVisitMethodInvocation(invocation, ctx); + if (method != null && (method.matches(mi) || matchesUntyped(mi))) { + return ReviewComment.java(mi, options.comment); + } + return mi; + } + + private boolean isFlaggedType(J.NewClass nc) { + if (nc.getType() != null && !(nc.getType() instanceof JavaType.Unknown)) { + return TypeUtils.isOfClassType(nc.getType(), options.fullyQualifiedTypeName); + } + TypeTree clazz = nc.getClazz(); + return clazz instanceof J.Identifier id + && options.fullyQualifiedTypeName.endsWith("." + id.getSimpleName()) + && ReviewComment.imports(getCursor(), options.fullyQualifiedTypeName); + } + + /** + * A static call with as many arguments as the pattern, on the simple name of the imported declaring + * type, on its fully qualified name, or statically imported. + */ + private boolean matchesUntyped(J.MethodInvocation mi) { + if (mi.getMethodType() != null) { + return false; + } + String pattern = options.methodPattern.trim(); + int space = pattern.indexOf(' '); + int open = pattern.indexOf('('); + String declaringType = pattern.substring(0, space); + String name = pattern.substring(space + 1, open).trim(); + String args = pattern.substring(open + 1, pattern.lastIndexOf(')')).trim(); + if (args.contains("..")) { + return false; + } + long arity = args.isEmpty() ? 0 : args.split(",").length; + long actual = mi.getArguments().stream().filter(a -> !(a instanceof J.Empty)).count(); + if (!name.equals(mi.getSimpleName()) || arity != actual) { + return false; + } + if (mi.getSelect() == null) { + return ReviewComment.importsStatic(getCursor(), declaringType, name); + } + if (mi.getSelect() instanceof J.Identifier select) { + return declaringType.endsWith("." + select.getSimpleName()) + && ReviewComment.imports(getCursor(), declaringType); + } + return declaringType.equals(qualifiedName(mi.getSelect())); + } + + private String qualifiedName(Expression expression) { + if (expression instanceof J.Identifier id) { + return id.getSimpleName(); + } + if (expression instanceof J.FieldAccess fa) { + String target = qualifiedName(fa.getTarget()); + return target == null ? null : target + "." + fa.getSimpleName(); + } + return null; + } + }; + } + } + + private static final class XmlRecipe extends Part { + XmlRecipe(FlagTypeOrMethodUse options) { + super(options); + } + + @Override + public String getDisplayName() { + return "Flag a bean of a type in XML"; + } + + @Override + public TreeVisitor<?, ExecutionContext> getVisitor() { + // not limited to the Camel XML DSL: the bean may be in a Spring XML file of its own + return new AbstractCamelXmlVisitor() { + @Override + public Xml.Tag doVisitTag(Xml.Tag tag, ExecutionContext ctx) { + Xml.Tag t = super.doVisitTag(tag, ctx); + return ReviewComment.xmlChildren(t, child -> "bean".equals(ReviewComment.localName(child)) + && child.getAttributes().stream().anyMatch(attr -> + ("class".equals(attr.getKeyAsString()) || "type".equals(attr.getKeyAsString())) + && options.isFlaggedTypeName(attr.getValueAsString())), + options.comment); + } + }; + } + } + + private static final class YamlRecipe extends Part { + YamlRecipe(FlagTypeOrMethodUse options) { + super(options); + } + + @Override + public String getDisplayName() { + return "Flag a bean of a type in the YAML DSL"; + } + + @Override + public TreeVisitor<?, ExecutionContext> getVisitor() { + return Preconditions.check(RecipesUtil.camelYamlDslPrecondition(), new ReviewComment.YamlVisitor(options.comment) { + @Override + public Yaml.Mapping.Entry doVisitMappingEntry(Yaml.Mapping.Entry entry, ExecutionContext ctx) { + Yaml.Mapping.Entry e = super.doVisitMappingEntry(entry, ctx); + if ("type".equals(e.getKey().getValue()) && e.getValue() instanceof Yaml.Scalar scalar + && options.isFlaggedTypeName(scalar.getValue())) { + return flag(e); + } + return e; + } + }); + } + } +} diff --git a/camel-upgrade-recipes/src/main/java/org/apache/camel/upgrade/camel418_6/ReviewComment.java b/camel-upgrade-recipes/src/main/java/org/apache/camel/upgrade/camel418_6/ReviewComment.java new file mode 100644 index 0000000..927630e --- /dev/null +++ b/camel-upgrade-recipes/src/main/java/org/apache/camel/upgrade/camel418_6/ReviewComment.java @@ -0,0 +1,183 @@ +/* + * 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.upgrade.camel418_6; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.function.Predicate; + +import org.apache.camel.upgrade.AbstractCamelYamlVisitor; +import org.apache.camel.upgrade.RecipesUtil; +import org.openrewrite.Cursor; +import org.openrewrite.ExecutionContext; +import org.openrewrite.internal.ListUtils; +import org.openrewrite.java.tree.J; +import org.openrewrite.java.tree.Space; +import org.openrewrite.java.tree.TextComment; +import org.openrewrite.marker.Markers; +import org.openrewrite.xml.tree.Content; +import org.openrewrite.xml.tree.Xml; +import org.openrewrite.yaml.tree.Yaml; + +/** + * Adds a review comment in front of code a migration cannot rewrite safely, once: a comment carrying the same JIRA + * key (the start of the comment text) is not added again, even if it was edited, so the recipes can run on every + * upgrade. + */ +final class ReviewComment { + + private ReviewComment() { + } + + /** The JIRA key a comment text starts with, for example {@code CAMEL-27052}. */ + static String key(String text) { + String trimmed = text.trim(); + int colon = trimmed.indexOf(':'); + return colon > 0 ? trimmed.substring(0, colon) : trimmed; + } + + /** The name of an XML tag without its namespace prefix ({@code toD} for {@code <c:toD>}). */ + static String localName(Xml.Tag tag) { + String name = tag.getName(); + return name.substring(name.indexOf(':') + 1); + } + + /** Whether the compilation unit of the cursor imports the class, by name or with its package. */ + static boolean imports(Cursor cursor, String fullyQualifiedName) { + J.CompilationUnit cu = cursor.firstEnclosing(J.CompilationUnit.class); + if (cu == null) { + return false; + } + String packageName = fullyQualifiedName.substring(0, fullyQualifiedName.lastIndexOf('.')); + return cu.getImports().stream().anyMatch(imp -> !imp.isStatic() + && (fullyQualifiedName.equals(imp.getTypeName()) + || "*".equals(imp.getQualid().getSimpleName()) && packageName.equals(imp.getPackageName()))); + } + + /** Whether the compilation unit of the cursor imports the static member of the class, by name or with {@code *}. */ + static boolean importsStatic(Cursor cursor, String fullyQualifiedName, String member) { + J.CompilationUnit cu = cursor.firstEnclosing(J.CompilationUnit.class); + if (cu == null) { + return false; + } + return cu.getImports().stream().anyMatch(imp -> imp.isStatic() + && fullyQualifiedName.equals(imp.getTypeName()) + && (member.equals(imp.getQualid().getSimpleName()) || "*".equals(imp.getQualid().getSimpleName()))); + } + + /** Adds {@code /* text * /} in front of a Java element, after the comments it already has. */ + static <T extends J> T java(T element, String text) { + Space prefix = element.getPrefix(); + String key = key(text) + ":"; + boolean present = prefix.getComments().stream() + .anyMatch(c -> c instanceof TextComment && ((TextComment) c).getText().contains(key)); + if (present) { + return element; + } + return element.withPrefix(prefix.withComments( + ListUtils.concat(prefix.getComments(), new TextComment(true, text, "", Markers.EMPTY)))); + } + + /** + * Adds an {@code <!-- text -->} sibling in front of each child tag of {@code parent} that {@code flag} accepts, + * unless one of the comments right in front of it carries the key. The comment is a node of its own, not text in + * the prefix of the tag, so that it is still recognised once the file has been parsed again. + */ + static Xml.Tag xmlChildren(Xml.Tag parent, Predicate<Xml.Tag> flag, String text) { + List<? extends Content> content = parent.getContent(); + if (content == null || content.isEmpty()) { + return parent; + } + String key = key(text) + ":"; + List<Content> newContent = null; + for (int i = 0; i < content.size(); i++) { + Content c = content.get(i); + if (c instanceof Xml.Tag && flag.test((Xml.Tag) c) && !precededByComment(content, i, key)) { + if (newContent == null) { + newContent = new ArrayList<>(content.subList(0, i)); + } + newContent.add(RecipesUtil.createXmlComment(text).withPrefix(c.getPrefix())); + } + if (newContent != null) { + newContent.add(c); + } + } + return newContent != null ? parent.withContent(newContent) : parent; + } + + private static boolean precededByComment(List<? extends Content> content, int index, String key) { + for (int i = index - 1; i >= 0 && content.get(i) instanceof Xml.Comment; i--) { + if (((Xml.Comment) content.get(i)).getText().contains(key)) { + return true; + } + } + return false; + } + + /** Returns the prefix of a YAML node with a {@code # text} line added, unless it already has one. */ + static String yamlPrefix(String prefix, String text) { + if (prefix.contains(key(text) + ":") || prefix.indexOf('\n') < 0) { + return prefix; + } + String indent = prefix.substring(prefix.lastIndexOf('\n') + 1); + return prefix + "#" + text + "\n" + indent; + } + + /** + * A Camel YAML DSL visitor that flags mapping entries. The comment goes on its own line in front of the entry; an + * entry that does not start a line, such as the first entry after the dash of a sequence item + * ({@code - toD: ...}) or an entry of a flow mapping ({@code {name: x}}), has no indentation of its own, so the + * comment goes in front of the sequence item that holds it instead. + */ + abstract static class YamlVisitor extends AbstractCamelYamlVisitor { + private final String text; + private final Set<UUID> flaggedItems = new HashSet<>(); + + YamlVisitor(String text) { + this.text = text; + } + + @Override + protected void clearLocalCache() { + flaggedItems.clear(); + } + + protected Yaml.Mapping.Entry flag(Yaml.Mapping.Entry entry) { + if (entry.getPrefix().indexOf('\n') >= 0) { + return entry.withPrefix(yamlPrefix(entry.getPrefix(), text)); + } + Yaml.Sequence.Entry item = getCursor().firstEnclosing(Yaml.Sequence.Entry.class); + if (item != null) { + flaggedItems.add(item.getId()); + } + return entry; + } + + @Override + public Yaml.Sequence doVisitSequence(Yaml.Sequence sequence, ExecutionContext ctx) { + Yaml.Sequence s = super.doVisitSequence(sequence, ctx); + if (flaggedItems.isEmpty()) { + return s; + } + return s.withEntries(ListUtils.map(s.getEntries(), + item -> flaggedItems.remove(item.getId()) ? item.withPrefix(yamlPrefix(item.getPrefix(), text)) : item)); + } + } +} diff --git a/camel-upgrade-recipes/src/main/resources/META-INF/rewrite/4.18.6.yaml b/camel-upgrade-recipes/src/main/resources/META-INF/rewrite/4.18.6.yaml index 6b37e69..8336755 100644 --- a/camel-upgrade-recipes/src/main/resources/META-INF/rewrite/4.18.6.yaml +++ b/camel-upgrade-recipes/src/main/resources/META-INF/rewrite/4.18.6.yaml @@ -41,6 +41,13 @@ recipeList: - org.apache.camel.upgrade.camel418_6.upgradeOpenstackSwiftHeaders - org.apache.camel.upgrade.camel418_6.upgradePubNubOverrideChannel - org.apache.camel.upgrade.camel418_6.migratePqcParameterSpecs + # review comments where nothing can be rewritten safely; these changes also ship in 4.22.3 and 4.24.0 + - org.apache.camel.upgrade.camel418_6.flagJaxbPartClassHeaders + - org.apache.camel.upgrade.camel418_6.flagSmppCredentialHeaders + - org.apache.camel.upgrade.camel418_6.flagRedisAggregationRepository + - org.apache.camel.upgrade.camel418_6.flagNettyPayloadHelperWithoutEndpoint + - org.apache.camel.upgrade.camel418_6.flagDynamicEndpointOptionValues + - org.apache.camel.upgrade.camel418_6.flagWhatsAppWebhookWithoutSecret --- ## https://github.com/apache/camel/blob/main/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_18.adoc#camel-openstack---the-remaining-swift-header-constants-follow-the-camel-naming-convention type: specs.openrewrite.org/v1beta/recipe @@ -178,3 +185,117 @@ recipeList: - org.openrewrite.java.ChangeType: oldFullyQualifiedTypeName: org.bouncycastle.pqc.jcajce.spec.SPHINCSPlusParameterSpec newFullyQualifiedTypeName: org.bouncycastle.jcajce.spec.SLHDSAParameterSpec +--- +## https://github.com/apache/camel/blob/main/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_18.adoc#camel-jaxb---the-part-class-and-namespace-headers-are-used-only-when-allowed +type: specs.openrewrite.org/v1beta/recipe +name: org.apache.camel.upgrade.camel418_6.flagJaxbPartClassHeaders +displayName: Flag the camel-jaxb part class and namespace headers where a route sets them +description: >- + CAMEL-27052 (4.18.6, 4.22.3 and 4.24.0): the JAXB data format uses the CamelJaxbPartClass and CamelJaxbPartNamespace + headers only when its new allowPartClassFromHeader option is true. Enabling it would undo the reason of the change, + so this adds a review comment where a route sets one of the headers. +preconditions: + - org.openrewrite.java.dependencies.search.ModuleHasDependency: + groupIdPattern: org.apache.camel + artifactIdPattern: camel-jaxb +recipeList: + - org.apache.camel.upgrade.camel418_6.FlagHeaderWhenSet: + headerNames: [CamelJaxbPartClass, CamelJaxbPartNamespace] + constantClass: org.apache.camel.converter.jaxb.JaxbConstants + constantNames: [JAXB_PART_CLASS, JAXB_PART_NAMESPACE] + comment: " CAMEL-27052: since Camel 4.18.6, 4.22.3 and 4.24.0 the JAXB data format ignores this header unless its allowPartClassFromHeader option is true (xml.in/xml.out.allowPartClassFromHeader with REST binding); otherwise its partClass and partNamespace apply." +--- +## https://github.com/apache/camel/blob/main/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_18.adoc#camel-smpp---the-system-id-and-password-headers-need-the-allowsystemidandpasswordfromheaders-option +type: specs.openrewrite.org/v1beta/recipe +name: org.apache.camel.upgrade.camel418_6.flagSmppCredentialHeaders +displayName: Flag the camel-smpp system id and password headers where a route sets them +description: >- + CAMEL-27227 (4.18.6, 4.22.3 and 4.24.0): the smpp producer uses the CamelSmppSystemId and CamelSmppPassword headers + only when the new allowSystemIdAndPasswordFromHeaders option is true. Enabling it would undo the reason of the + change, so this adds a review comment where a route sets one of the headers. +preconditions: + - org.openrewrite.java.dependencies.search.ModuleHasDependency: + groupIdPattern: org.apache.camel + artifactIdPattern: camel-smpp +recipeList: + - org.apache.camel.upgrade.camel418_6.FlagHeaderWhenSet: + headerNames: [CamelSmppSystemId, CamelSmppPassword] + constantClass: org.apache.camel.component.smpp.SmppConstants + constantNames: [SYSTEM_ID, PASSWORD] + comment: " CAMEL-27227: since Camel 4.18.6, 4.22.3 and 4.24.0 the smpp producer connects with its systemId and password options and ignores this header, which it used only with lazySessionCreation=true and both CamelSmppSystemId and CamelSmppPassword set, unless allowSystemIdAndPasswordFromHeaders=true is set on the endpoint or the component." +--- +## https://github.com/apache/camel/blob/main/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_18.adoc#camel-redis---redisaggregationrepository-stores-exchanges-in-java-serialization-read-through-a-deserialization-filter +type: specs.openrewrite.org/v1beta/recipe +name: org.apache.camel.upgrade.camel418_6.flagRedisAggregationRepository +displayName: Flag RedisAggregationRepository for its new storage format +description: >- + CAMEL-27225 (4.18.6, 4.22.3 and 4.24.0): RedisAggregationRepository stores exchanges in Java serialization, read + through a deserialization filter, and does not read the entries stored by older versions. Whether to drain the + repository first, or to keep the codec the old entries were written with (the codec of the Redisson client) until + they are gone, depends on the deployment, so this adds a review comment where the repository is created or declared + as a bean. +preconditions: + - org.openrewrite.java.dependencies.search.ModuleHasDependency: + groupIdPattern: org.apache.camel + artifactIdPattern: camel-redis +recipeList: + - org.apache.camel.upgrade.camel418_6.FlagTypeOrMethodUse: + fullyQualifiedTypeName: org.apache.camel.component.redis.processor.aggregate.RedisAggregationRepository + comment: " CAMEL-27225: since Camel 4.18.6, 4.22.3 and 4.24.0 this repository stores exchanges in Java serialization, read through its deserializationFilter, and does not read the entries stored by older versions: complete the aggregations before upgrading, or set its codec to the one the old entries were written with (the codec of the Redisson client, by default new org.redisson.codec.Kryo5Codec()) until they are gone." +--- +## https://github.com/apache/camel/blob/main/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_18.adoc#camel-netty---transferexchange-requires-explicit-endpoint-configuration +type: specs.openrewrite.org/v1beta/recipe +name: org.apache.camel.upgrade.camel418_6.flagNettyPayloadHelperWithoutEndpoint +displayName: Flag the NettyPayloadHelper setIn and setOut calls without an endpoint +description: >- + CAMEL-26587 (4.18.6, 4.22.3 and 4.24.0): NettyPayloadHelper.setIn(Exchange, Object) and setOut(Exchange, Object) are + deprecated and no longer unmarshal a DefaultExchangeHolder; the new overloads take the NettyEndpoint, whose + transferExchange option decides. Which endpoint to pass is up to the calling code, so this adds a review comment + where the old methods are called. +preconditions: + - org.openrewrite.java.dependencies.search.ModuleHasDependency: + groupIdPattern: org.apache.camel + artifactIdPattern: camel-netty* +recipeList: + - org.apache.camel.upgrade.camel418_6.FlagTypeOrMethodUse: + methodPattern: org.apache.camel.component.netty.NettyPayloadHelper setIn(org.apache.camel.Exchange, java.lang.Object) + comment: " CAMEL-26587: since Camel 4.18.6, 4.22.3 and 4.24.0 this method no longer unmarshals a DefaultExchangeHolder: call the overload that takes the NettyEndpoint, whose transferExchange option decides." + - org.apache.camel.upgrade.camel418_6.FlagTypeOrMethodUse: + methodPattern: org.apache.camel.component.netty.NettyPayloadHelper setOut(org.apache.camel.Exchange, java.lang.Object) + comment: " CAMEL-26587: since Camel 4.18.6, 4.22.3 and 4.24.0 this method no longer unmarshals a DefaultExchangeHolder: call the overload that takes the NettyEndpoint, whose transferExchange option decides." +--- +## https://github.com/apache/camel/blob/main/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_18.adoc#camel-core---option-values-of-a-dynamic-endpoint-are-bound-as-literal-text +type: specs.openrewrite.org/v1beta/recipe +name: org.apache.camel.upgrade.camel418_6.flagDynamicEndpointOptionValues +displayName: Flag the option values of dynamic endpoints that are now bound as literal text +description: >- + CAMEL-27160 (4.18.6, 4.22.3 and 4.24.0): the options of an endpoint that toD, enrich, pollEnrich, wireTap, + recipientList, routingSlip or dynamicRouter compute per message are bound as literal text: a #class: or #property: + value is not resolved, and a $simpleEllipsis in RAW() is not evaluated. The replacement (a registered bean referred to + with #bean:, or a property placeholder) depends on the application, so this adds a review comment where such a + value is written in the uri of one of these EIPs. +recipeList: + - org.apache.camel.upgrade.camel418_6.FlagEndpointUri: + eips: [toD, enrich, pollEnrich, wireTap, recipientList, routingSlip, dynamicRouter] + uriPattern: '(?:^|[?&])[^=&?]+=#(?:class|property):|RAW[({][^)}]*\$simple\{' + comment: " CAMEL-27160: since Camel 4.18.6, 4.22.3 and 4.24.0 the options of an endpoint computed per message are bound as literal text: #class: and #property: values are not resolved, and $simple{...} in RAW() is not evaluated. Register a bean and refer to it with #bean:, or use a {{...}} property placeholder." +--- +## https://github.com/apache/camel/blob/main/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_18.adoc#camel-whatsapp---webhook-events-are-verified-by-default +type: specs.openrewrite.org/v1beta/recipe +name: org.apache.camel.upgrade.camel418_6.flagWhatsAppWebhookWithoutSecret +displayName: Flag the camel-whatsapp webhook consumers without a webhookSecret +description: >- + CAMEL-26281 (4.18.6, 4.22.3 and 4.24.0): a whatsapp webhook now verifies the X-Hub-Signature-256 signature of every + event with webhookSecret, and a webhook route without it fails to start. The secret is the app secret of the + deployment, so this adds a review comment to a webhook:whatsapp: consumer whose uri or parameters set neither a + non-empty webhookSecret nor webhookVerification=false (they may also be set on the component). +preconditions: + - org.openrewrite.java.dependencies.search.ModuleHasDependency: + groupIdPattern: org.apache.camel + artifactIdPattern: camel-whatsapp +recipeList: + - org.apache.camel.upgrade.camel418_6.FlagEndpointUri: + eips: [from] + uriPattern: 'webhook:whatsapp:' + unlessPattern: '(?:^|[?&])(?:webhookSecret|webhook-secret)=[^&\s]|(?:^|[?&])(?:webhookVerification|webhook-verification)=false' + comment: " CAMEL-26281: since Camel 4.18.6, 4.22.3 and 4.24.0 a whatsapp webhook verifies the X-Hub-Signature-256 of every event with webhookSecret and fails to start without it: set webhookSecret to the app secret (here or on the component), or webhookVerification=false to accept unverified events." diff --git a/camel-upgrade-recipes/src/main/resources/META-INF/rewrite/4.22.3.yaml b/camel-upgrade-recipes/src/main/resources/META-INF/rewrite/4.22.3.yaml index 4028833..406072f 100644 --- a/camel-upgrade-recipes/src/main/resources/META-INF/rewrite/4.22.3.yaml +++ b/camel-upgrade-recipes/src/main/resources/META-INF/rewrite/4.22.3.yaml @@ -39,3 +39,9 @@ recipeList: ## inherited from patch recipes: these changes also ship in 4.18.6 - org.apache.camel.upgrade.camel418_6.upgradeOpenstackSwiftHeaders - org.apache.camel.upgrade.camel418_6.upgradePubNubOverrideChannel + - org.apache.camel.upgrade.camel418_6.flagJaxbPartClassHeaders + - org.apache.camel.upgrade.camel418_6.flagSmppCredentialHeaders + - org.apache.camel.upgrade.camel418_6.flagRedisAggregationRepository + - org.apache.camel.upgrade.camel418_6.flagNettyPayloadHelperWithoutEndpoint + - org.apache.camel.upgrade.camel418_6.flagDynamicEndpointOptionValues + - org.apache.camel.upgrade.camel418_6.flagWhatsAppWebhookWithoutSecret diff --git a/camel-upgrade-recipes/src/test/java/org/apache/camel/upgrade/CamelUpdate418_6Test.java b/camel-upgrade-recipes/src/test/java/org/apache/camel/upgrade/CamelUpdate418_6Test.java index d87c1c5..fe93c59 100644 --- a/camel-upgrade-recipes/src/test/java/org/apache/camel/upgrade/CamelUpdate418_6Test.java +++ b/camel-upgrade-recipes/src/test/java/org/apache/camel/upgrade/CamelUpdate418_6Test.java @@ -37,6 +37,13 @@ import static org.openrewrite.yaml.Assertions.yaml; */ public class CamelUpdate418_6Test implements RewriteTest { + private static final String JAXB_COMMENT = " CAMEL-27052: since Camel 4.18.6, 4.22.3 and 4.24.0 the JAXB data format ignores this header unless its allowPartClassFromHeader option is true (xml.in/xml.out.allowPartClassFromHeader with REST binding); otherwise its partClass and partNamespace apply."; + private static final String SMPP_COMMENT = " CAMEL-27227: since Camel 4.18.6, 4.22.3 and 4.24.0 the smpp producer connects with its systemId and password options and ignores this header, which it used only with lazySessionCreation=true and both CamelSmppSystemId and CamelSmppPassword set, unless allowSystemIdAndPasswordFromHeaders=true is set on the endpoint or the component."; + private static final String REDIS_COMMENT = " CAMEL-27225: since Camel 4.18.6, 4.22.3 and 4.24.0 this repository stores exchanges in Java serialization, read through its deserializationFilter, and does not read the entries stored by older versions: complete the aggregations before upgrading, or set its codec to the one the old entries were written with (the codec of the Redisson client, by default new org.redisson.codec.Kryo5Codec()) until they are gone."; + private static final String NETTY_COMMENT = " CAMEL-26587: since Camel 4.18.6, 4.22.3 and 4.24.0 this method no longer unmarshals a DefaultExchangeHolder: call the overload that takes the NettyEndpoint, whose transferExchange option decides."; + private static final String DYNAMIC_COMMENT = " CAMEL-27160: since Camel 4.18.6, 4.22.3 and 4.24.0 the options of an endpoint computed per message are bound as literal text: #class: and #property: values are not resolved, and $simple{...} in RAW() is not evaluated. Register a bean and refer to it with #bean:, or use a {{...}} property placeholder."; + private static final String WHATSAPP_COMMENT = " CAMEL-26281: since Camel 4.18.6, 4.22.3 and 4.24.0 a whatsapp webhook verifies the X-Hub-Signature-256 of every event with webhookSecret and fails to start without it: set webhookSecret to the app secret (here or on the component), or webhookVerification=false to accept unverified events."; + @Override public void defaults(RecipeSpec spec) { CamelTestUtil.recipe(spec, CamelTestUtil.CamelVersion.v4_18_6) @@ -566,4 +573,583 @@ public class CamelUpdate418_6Test implements RewriteTest { ) ); } + + @Test + void flagJaxbPartClassHeadersJava() { + rewriteRun( + mavenProject("test-jaxb", + CamelTestUtil.pomXmlSpec("camel-jaxb", CamelTestUtil.CamelVersion.v4_18_5), + //language=java + java( + """ + import org.apache.camel.builder.RouteBuilder; + import org.apache.camel.converter.jaxb.JaxbConstants; + + public class JaxbRoute extends RouteBuilder { + @Override + public void configure() { + from("direct:marshal") + .setHeader("CamelJaxbPartClass", constant("com.example.Order")) + .setHeader(JaxbConstants.JAXB_PART_NAMESPACE, constant("{urn:orders}order")) + .log("part class ${header.CamelJaxbPartClass}") + .marshal().jaxb("com.example"); + } + } + """, + """ + import org.apache.camel.builder.RouteBuilder; + import org.apache.camel.converter.jaxb.JaxbConstants; + + public class JaxbRoute extends RouteBuilder { + @Override + public void configure() { + from("direct:marshal") + .setHeader(/*%1$s*/"CamelJaxbPartClass", constant("com.example.Order")) + .setHeader(/*%1$s*/JaxbConstants.JAXB_PART_NAMESPACE, constant("{urn:orders}order")) + .log("part class ${header.CamelJaxbPartClass}") + .marshal().jaxb("com.example"); + } + } + """.formatted(JAXB_COMMENT) + ) + ) + ); + } + + @Test + void flagJaxbPartClassHeadersXmlAndYaml() { + rewriteRun( + mavenProject("test-jaxb-dsl", + CamelTestUtil.pomXmlSpec("camel-jaxb", CamelTestUtil.CamelVersion.v4_18_5), + //language=xml + xml( + """ + <route xmlns="http://camel.apache.org/schema/spring"> + <from uri="direct:marshal"/> + <setHeader name="CamelJaxbPartClass"> + <constant>com.example.Order</constant> + </setHeader> + <to uri="mock:out"/> + </route> + """, + """ + <route xmlns="http://camel.apache.org/schema/spring"> + <from uri="direct:marshal"/> + <!--%1$s--> + <setHeader name="CamelJaxbPartClass"> + <constant>com.example.Order</constant> + </setHeader> + <to uri="mock:out"/> + </route> + """.formatted(JAXB_COMMENT) + ), + //language=yaml + yaml( + """ + - route: + from: + uri: "direct:marshal" + steps: + - setHeader: + constant: "com.example.Order" + name: CamelJaxbPartClass + - to: + uri: "mock:out" + """, + """ + - route: + from: + uri: "direct:marshal" + steps: + - setHeader: + constant: "com.example.Order" + #%1$s + name: CamelJaxbPartClass + - to: + uri: "mock:out" + """.formatted(JAXB_COMMENT) + ) + ) + ); + } + + @Test + void flagSmppCredentialHeaders() { + rewriteRun( + mavenProject("test-smpp", + CamelTestUtil.pomXmlSpec("camel-smpp", CamelTestUtil.CamelVersion.v4_18_5), + //language=java + java( + """ + import org.apache.camel.builder.RouteBuilder; + import org.apache.camel.component.smpp.SmppConstants; + + public class SmppRoute extends RouteBuilder { + @Override + public void configure() { + from("direct:sms") + .setHeader(SmppConstants.SYSTEM_ID, simple("${header.tenantId}")) + .process(exchange -> exchange.getIn().setHeader("CamelSmppPassword", "secret")) + .setHeader(SmppConstants.DEST_ADDR, constant("12345")) + .to("smpp://smsc?lazySessionCreation=true"); + } + } + """, + """ + import org.apache.camel.builder.RouteBuilder; + import org.apache.camel.component.smpp.SmppConstants; + + public class SmppRoute extends RouteBuilder { + @Override + public void configure() { + from("direct:sms") + .setHeader(/*%1$s*/SmppConstants.SYSTEM_ID, simple("${header.tenantId}")) + .process(exchange -> exchange.getIn().setHeader(/*%1$s*/"CamelSmppPassword", "secret")) + .setHeader(SmppConstants.DEST_ADDR, constant("12345")) + .to("smpp://smsc?lazySessionCreation=true"); + } + } + """.formatted(SMPP_COMMENT) + ) + ) + ); + } + + @Test + void flagRedisAggregationRepository() { + rewriteRun( + mavenProject("test-redis", + CamelTestUtil.pomXmlSpec("camel-redis", CamelTestUtil.CamelVersion.v4_18_5), + //language=java + java( + """ + import org.apache.camel.builder.RouteBuilder; + import org.apache.camel.component.redis.processor.aggregate.RedisAggregationRepository; + + public class AggregateRoute extends RouteBuilder { + @Override + public void configure() { + RedisAggregationRepository repository = new RedisAggregationRepository("orders", "localhost:6379"); + from("direct:in") + .aggregate(header("orderId"), (oldExchange, newExchange) -> newExchange) + .aggregationRepository(repository) + .completionSize(3) + .to("mock:out"); + } + } + """, + """ + import org.apache.camel.builder.RouteBuilder; + import org.apache.camel.component.redis.processor.aggregate.RedisAggregationRepository; + + public class AggregateRoute extends RouteBuilder { + @Override + public void configure() { + RedisAggregationRepository repository = /*%1$s*/new RedisAggregationRepository("orders", "localhost:6379"); + from("direct:in") + .aggregate(header("orderId"), (oldExchange, newExchange) -> newExchange) + .aggregationRepository(repository) + .completionSize(3) + .to("mock:out"); + } + } + """.formatted(REDIS_COMMENT) + ), + //language=yaml + yaml( + """ + - beans: + - name: ordersRepository + type: org.apache.camel.component.redis.processor.aggregate.RedisAggregationRepository + constructors: + "0": orders + "1": "localhost:6379" + """, + """ + - beans: + - name: ordersRepository + #%1$s + type: org.apache.camel.component.redis.processor.aggregate.RedisAggregationRepository + constructors: + "0": orders + "1": "localhost:6379" + """.formatted(REDIS_COMMENT) + ) + ) + ); + } + + @Test + void flagNettyPayloadHelperWithoutEndpoint() { + rewriteRun( + mavenProject("test-netty", + CamelTestUtil.pomXmlSpec("camel-netty", CamelTestUtil.CamelVersion.v4_18_5), + //language=java + java( + """ + import org.apache.camel.Exchange; + import org.apache.camel.component.netty.NettyEndpoint; + import org.apache.camel.component.netty.NettyPayloadHelper; + + import static org.apache.camel.component.netty.NettyPayloadHelper.setOut; + + public class PayloadCodec { + void read(Exchange exchange, Object payload) { + NettyPayloadHelper.setIn(exchange, payload); + } + + void write(Exchange exchange, Object payload) { + setOut(exchange, payload); + } + + void reply(NettyEndpoint endpoint, Exchange exchange, Object payload) { + NettyPayloadHelper.setOut(endpoint, exchange, payload); + } + } + """, + """ + import org.apache.camel.Exchange; + import org.apache.camel.component.netty.NettyEndpoint; + import org.apache.camel.component.netty.NettyPayloadHelper; + + import static org.apache.camel.component.netty.NettyPayloadHelper.setOut; + + public class PayloadCodec { + void read(Exchange exchange, Object payload) { + /*%1$s*/NettyPayloadHelper.setIn(exchange, payload); + } + + void write(Exchange exchange, Object payload) { + /*%1$s*/setOut(exchange, payload); + } + + void reply(NettyEndpoint endpoint, Exchange exchange, Object payload) { + NettyPayloadHelper.setOut(endpoint, exchange, payload); + } + } + """.formatted(NETTY_COMMENT) + ) + ) + ); + } + + @Test + void flagDynamicEndpointOptionValuesJava() { + rewriteRun( + mavenProject("test-dynamic", + CamelTestUtil.pomXmlSpec("camel-core", CamelTestUtil.CamelVersion.v4_18_5), + //language=java + java( + """ + import org.apache.camel.builder.RouteBuilder; + + public class DynamicRoute extends RouteBuilder { + @Override + public void configure() { + from("direct:audit") + .to("log:static?exchangeFormatter=#class:com.foo.MyFormatter") + .toD("log:audit?exchangeFormatter=#class:com.foo.MyFormatter&marker=${header.customer}") + .toD("log:audit?exchangeFormatter=#bean:myFormatter&marker=${header.customer}") + .toD("log:out", "log:a?exchangeFormatter=#class:com.foo.NotAUri", "result") + .enrich(simple("ftp:joe@${header.host}?password=RAW(pre-$simple{env:FTP_PASSWORD})")) + .enrich("direct:lookup", (original, resource) -> { + original.getIn().setHeader("next", "log:x?exchangeFormatter=#class:com.foo.Other"); + return original; + }) + .recipientList(simple("sql:${header.query}?dataSource=#property:ds")); + Audit.toD("log:audit?exchangeFormatter=#class:com.foo.MyFormatter"); + } + + static class Audit { + static void toD(String uri) { + } + } + } + """, + """ + import org.apache.camel.builder.RouteBuilder; + + public class DynamicRoute extends RouteBuilder { + @Override + public void configure() { + from("direct:audit") + .to("log:static?exchangeFormatter=#class:com.foo.MyFormatter") + .toD(/*%1$s*/"log:audit?exchangeFormatter=#class:com.foo.MyFormatter&marker=${header.customer}") + .toD("log:audit?exchangeFormatter=#bean:myFormatter&marker=${header.customer}") + .toD("log:out", "log:a?exchangeFormatter=#class:com.foo.NotAUri", "result") + .enrich(simple(/*%1$s*/"ftp:joe@${header.host}?password=RAW(pre-$simple{env:FTP_PASSWORD})")) + .enrich("direct:lookup", (original, resource) -> { + original.getIn().setHeader("next", "log:x?exchangeFormatter=#class:com.foo.Other"); + return original; + }) + .recipientList(simple(/*%1$s*/"sql:${header.query}?dataSource=#property:ds")); + Audit.toD("log:audit?exchangeFormatter=#class:com.foo.MyFormatter"); + } + + static class Audit { + static void toD(String uri) { + } + } + } + """.formatted(DYNAMIC_COMMENT) + ) + ) + ); + } + + @Test + void flagDynamicEndpointOptionValuesXmlAndYaml() { + rewriteRun( + mavenProject("test-dynamic-dsl", + CamelTestUtil.pomXmlSpec("camel-core", CamelTestUtil.CamelVersion.v4_18_5), + //language=xml + xml( + """ + <route xmlns="http://camel.apache.org/schema/spring"> + <from uri="direct:audit"/> + <toD uri="log:audit?exchangeFormatter=#class:com.foo.MyFormatter&marker=${header.customer}"/> + <to uri="log:static?exchangeFormatter=#class:com.foo.MyFormatter"/> + </route> + """, + """ + <route xmlns="http://camel.apache.org/schema/spring"> + <from uri="direct:audit"/> + <!--%1$s--> + <toD uri="log:audit?exchangeFormatter=#class:com.foo.MyFormatter&marker=${header.customer}"/> + <to uri="log:static?exchangeFormatter=#class:com.foo.MyFormatter"/> + </route> + """.formatted(DYNAMIC_COMMENT) + ), + //language=yaml + yaml( + """ + - route: + from: + uri: "direct:audit" + steps: + - toD: + id: audit + uri: "log:audit?exchangeFormatter=#class:com.foo.MyFormatter&marker=${header.customer}" + """, + """ + - route: + from: + uri: "direct:audit" + steps: + - toD: + id: audit + #%1$s + uri: "log:audit?exchangeFormatter=#class:com.foo.MyFormatter&marker=${header.customer}" + """.formatted(DYNAMIC_COMMENT) + ) + ) + ); + } + + @Test + void flagWhatsAppWebhookWithoutSecret() { + rewriteRun( + mavenProject("test-whatsapp", + CamelTestUtil.pomXmlSpec("camel-whatsapp", CamelTestUtil.CamelVersion.v4_18_5), + //language=java + java( + """ + import org.apache.camel.builder.RouteBuilder; + + public class WhatsAppRoute extends RouteBuilder { + @Override + public void configure() { + from("webhook:whatsapp:123456?authorizationToken={{token}}").to("direct:events"); + from("webhook:whatsapp:654321?authorizationToken={{token}}&webhookSecret={{secret}}").to("direct:events"); + from("webhook:whatsapp:111111?authorizationToken={{token}}&webhookVerification=true").to("direct:events"); + from("webhook:whatsapp:222222?authorizationToken={{token}}&webhookVerification=false").to("direct:events"); + from("webhook:whatsapp:333333?authorizationToken={{token}}&webhookSecret=").to("direct:events"); + from("direct:send").to("whatsapp:123456?authorizationToken={{token}}"); + } + } + """, + """ + import org.apache.camel.builder.RouteBuilder; + + public class WhatsAppRoute extends RouteBuilder { + @Override + public void configure() { + from(/*%1$s*/"webhook:whatsapp:123456?authorizationToken={{token}}").to("direct:events"); + from("webhook:whatsapp:654321?authorizationToken={{token}}&webhookSecret={{secret}}").to("direct:events"); + from(/*%1$s*/"webhook:whatsapp:111111?authorizationToken={{token}}&webhookVerification=true").to("direct:events"); + from("webhook:whatsapp:222222?authorizationToken={{token}}&webhookVerification=false").to("direct:events"); + from(/*%1$s*/"webhook:whatsapp:333333?authorizationToken={{token}}&webhookSecret=").to("direct:events"); + from("direct:send").to("whatsapp:123456?authorizationToken={{token}}"); + } + } + """.formatted(WHATSAPP_COMMENT) + ), + //language=yaml + yaml( + """ + - route: + from: + uri: "webhook:whatsapp:123456" + parameters: + authorizationToken: "{{token}}" + webhookSecret: "{{secret}}" + steps: + - to: + uri: "direct:events" + """ + ), + //language=yaml + yaml( + """ + - route: + from: + uri: "webhook:whatsapp:654321" + parameters: + authorizationToken: "{{token}}" + steps: + - log: + message: "remember the webhookSecret=..." + """, + """ + - route: + from: + #%1$s + uri: "webhook:whatsapp:654321" + parameters: + authorizationToken: "{{token}}" + steps: + - log: + message: "remember the webhookSecret=..." + """.formatted(WHATSAPP_COMMENT) + ) + ) + ); + } + + @Test + void flagsNeedTheirComponent() { + rewriteRun( + spec -> spec.expectedCyclesThatMakeChanges(CamelTestUtil.isRecipeOverridden() ? 1 : 0), + mavenProject("test-no-flagged-components", + CamelTestUtil.pomXmlSpec("camel-core", CamelTestUtil.CamelVersion.v4_18_5), + //language=java + java( + """ + import org.apache.camel.builder.RouteBuilder; + + public class PlainRoute extends RouteBuilder { + @Override + public void configure() { + from("direct:in") + .setHeader("CamelJaxbPartClass", constant("com.example.Order")) + .setHeader("CamelSmppPassword", constant("secret")) + .to("mock:out"); + } + } + """ + ) + ) + ); + } + + @Test + void flagCompactYamlAndPrefixedXml() { + rewriteRun( + mavenProject("test-compact", + CamelTestUtil.pomXmlSpec("camel-jaxb", CamelTestUtil.CamelVersion.v4_18_5), + //language=yaml + yaml( + """ + - route: + from: + uri: "direct:audit" + steps: + - toD: "log:audit?exchangeFormatter=#class:com.foo.MyFormatter" + - setHeader: {name: CamelJaxbPartClass, constant: com.example.Order} + - toD: + description: "log:a?exchangeFormatter=#class:not.a.Uri" + uri: "log:audit" + - toD: + uri: "log:audit" + parameters: + exchangeFormatter: "#class:com.foo.MyFormatter" + """, + """ + - route: + from: + uri: "direct:audit" + steps: + #%1$s + - toD: "log:audit?exchangeFormatter=#class:com.foo.MyFormatter" + #%2$s + - setHeader: {name: CamelJaxbPartClass, constant: com.example.Order} + - toD: + description: "log:a?exchangeFormatter=#class:not.a.Uri" + uri: "log:audit" + - toD: + uri: "log:audit" + parameters: + #%1$s + exchangeFormatter: "#class:com.foo.MyFormatter" + """.formatted(DYNAMIC_COMMENT, JAXB_COMMENT) + ), + //language=xml + xml( + """ + <c:routes xmlns:c="http://camel.apache.org/schema/spring"> + <c:route> + <c:from uri="direct:audit"/> + <c:toD uri="log:audit?exchangeFormatter=#class:com.foo.MyFormatter"/> + </c:route> + </c:routes> + """, + """ + <c:routes xmlns:c="http://camel.apache.org/schema/spring"> + <c:route> + <c:from uri="direct:audit"/> + <!--%1$s--> + <c:toD uri="log:audit?exchangeFormatter=#class:com.foo.MyFormatter"/> + </c:route> + </c:routes> + """.formatted(DYNAMIC_COMMENT) + ) + ) + ); + } + + @Test + void flagsAreNotDuplicatedWhenEdited() { + // a comment with the same JIRA key, even edited by the user, is not added again + rewriteRun( + spec -> spec.expectedCyclesThatMakeChanges(CamelTestUtil.isRecipeOverridden() ? 1 : 0), + mavenProject("test-reviewed", + CamelTestUtil.pomXmlSpec("camel-core", CamelTestUtil.CamelVersion.v4_18_5), + //language=java + java( + """ + import org.apache.camel.builder.RouteBuilder; + + public class ReviewedRoute extends RouteBuilder { + @Override + public void configure() { + from("direct:audit") + .toD(/* CAMEL-27160: reviewed, MyFormatter is registered */"log:audit?exchangeFormatter=#class:com.foo.MyFormatter"); + } + } + """ + ), + //language=xml + xml( + """ + <route xmlns="http://camel.apache.org/schema/spring"> + <from uri="direct:audit"/> + <!-- CAMEL-27160: reviewed --> + <!-- the formatter is registered --> + <toD uri="log:audit?exchangeFormatter=#class:com.foo.MyFormatter"/> + </route> + """ + ) + ) + ); + } } diff --git a/release_notes.adoc b/release_notes.adoc index d665375..43c0f0a 100644 --- a/release_notes.adoc +++ b/release_notes.adoc @@ -199,7 +199,7 @@ NOTE: At the time these recipes were written, Camel 4.23.0 had not yet been rele === Summary -Patch recipes for Camel 4.22.3 (`camel422_3.CamelMigrationRecipe`), chained by the 4.22 LTS aggregates and by `camel424.CamelMigrationRecipe` (Camel 4.23.0 does not have these changes). Both changes also ship in 4.18.6, so their recipes live in `camel418_6` and the 4.22.3 chain references them. The backports keep their upgrade guide notes on `main`, so the recipes are triaged from the 4.22.3 section on `main` and checked against the code at the `camel-4.22.3` tag: not every item of that [...] +Patch recipes for Camel 4.22.3 (`camel422_3.CamelMigrationRecipe`), chained by the 4.22 LTS aggregates and by `camel424.CamelMigrationRecipe` (Camel 4.23.0 does not have these changes). All of them also ship in 4.18.6, so their recipes live in `camel418_6` and the 4.22.3 chain references them. The backports keep their upgrade guide notes on `main`, so the recipes are triaged from the 4.22.3 section on `main` and checked against the code at the `camel-4.22.3` tag: not every item of that s [...] === Migration coverage @@ -215,9 +215,13 @@ Patch recipes for Camel 4.22.3 (`camel422_3.CamelMigrationRecipe`), chained by t | ⚠️ Partial | Inherited from the 4.18.6 patch recipe `camel418_6.upgradePubNubOverrideChannel`; see <<4.18.6>>. +| https://github.com/apache/camel/blob/main/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_22.adoc#upgrading-from-4222-to-4223[camel-jaxb, camel-smpp, camel-redis, camel-netty, camel-core dynamic endpoints, camel-whatsapp] +| ⚠️ Partial +| Inherited from the 4.18.6 patch recipes `camel418_6.flag*`, as the same changes ship in 4.22.3; see <<4.18.6>>. + | https://github.com/apache/camel/blob/main/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_22.adoc#upgrading-from-4222-to-4223[Other 4.22.3 changes] | ❌ None -| Behaviour or secure-default changes, see the guide. netty `NettyPayloadHelper.setIn/setOut`: the new overloads need the `NettyEndpoint`, manual. +| Behaviour or secure-default changes, see the guide. |=== NOTE: Camel 4.23.0 does not have the openstack change: an upgrade from 4.22.3 to 4.23.0 brings back the `X-*` Swift header names on the Camel side. The recipes cannot undo a rename; 4.24.0 has the `CamelOpenstackSwift*` names again. @@ -249,6 +253,30 @@ Patch recipes for Camel 4.18.6 (`camel418_6.CamelMigrationRecipe`). The backport | https://github.com/apache/camel/blob/main/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_18.adoc#camel-cxf-camel-cxfrs---the-former-operationname-and-operationnamespace-headers-are-not-sent[camel-cxf, camel-cxfrs: the former `operationName` and `operationNamespace` headers are not sent] | ⚠️ Partial | The rename to `CamelCxfOperationName` / `CamelCxfOperationNamespace` shipped in 4.18.3 and 4.21.0 without a recipe; 4.18.6 (and 4.22.3, 4.24.0) also filters the former names out of the HTTP headers. New `camel418_3.upgradeCxfHeaders`, chained by `camel418_3` and referenced from `camel421`: the Endpoint DSL builders `cxf().operationName()` / `operationNamespace()` and `cxfrs().operationName()`, and the literal header names in Java header methods, Simple, XML and YAML DSL, gated on `came [...] + +| https://github.com/apache/camel/blob/main/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_18.adoc#camel-jaxb---the-part-class-and-namespace-headers-are-used-only-when-allowed[camel-jaxb: part class and namespace headers need `allowPartClassFromHeader`] (CAMEL-27052) +| ⚠️ Partial +| `camel418_6.flagJaxbPartClassHeaders`: a review comment where a route sets `CamelJaxbPartClass` or `CamelJaxbPartNamespace` (`setHeader` in Java, XML and YAML, `Message.setHeader`, `JaxbConstants`), gated on `camel-jaxb`. Enabling the option would undo the reason of the change, so it is not set automatically. + +| https://github.com/apache/camel/blob/main/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_18.adoc#camel-smpp---the-system-id-and-password-headers-need-the-allowsystemidandpasswordfromheaders-option[camel-smpp: system id and password headers need `allowSystemIdAndPasswordFromHeaders`] (CAMEL-27227) +| ⚠️ Partial +| `camel418_6.flagSmppCredentialHeaders`: a review comment where a route sets `CamelSmppSystemId` or `CamelSmppPassword` (also `SmppConstants`), gated on `camel-smpp`. The producer used them only with `lazySessionCreation=true` and both headers set. + +| https://github.com/apache/camel/blob/main/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_18.adoc#camel-redis---redisaggregationrepository-stores-exchanges-in-java-serialization-read-through-a-deserialization-filter[camel-redis: `RedisAggregationRepository` storage format] (CAMEL-27225) +| ⚠️ Partial +| `camel418_6.flagRedisAggregationRepository`: a review comment where Java code creates the repository, at a `<bean class>` / `<bean type>` and at a YAML DSL bean `type`, gated on `camel-redis`. Whether to drain it, or to keep the codec the old entries were written with for a while, depends on the deployment. + +| https://github.com/apache/camel/blob/main/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_18.adoc#camel-netty---transferexchange-requires-explicit-endpoint-configuration[camel-netty: `NettyPayloadHelper.setIn/setOut` without an endpoint] (CAMEL-26587) +| ⚠️ Partial +| `camel418_6.flagNettyPayloadHelperWithoutEndpoint`: a review comment at the calls of the deprecated two-argument methods, gated on `camel-netty*`. + +| https://github.com/apache/camel/blob/main/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_18.adoc#camel-core---option-values-of-a-dynamic-endpoint-are-bound-as-literal-text[camel-core: option values of a dynamic endpoint are bound as literal text] (CAMEL-27160) +| ⚠️ Partial +| `camel418_6.flagDynamicEndpointOptionValues`: a review comment where the uri written in `toD`, `enrich`, `pollEnrich`, `wireTap`, `recipientList`, `routingSlip` or `dynamicRouter` (Java, XML and YAML DSL, including the YAML `parameters`) has a `#class:` or `#property:` option value or a `$simple{...}` in `RAW()`. A uri built by code is not seen. + +| https://github.com/apache/camel/blob/main/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_18.adoc#camel-whatsapp---webhook-events-are-verified-by-default[camel-whatsapp: webhook events are verified by default] (CAMEL-26281) +| ⚠️ Partial +| `camel418_6.flagWhatsAppWebhookWithoutSecret`: a review comment at a `webhook:whatsapp:` consumer whose uri (or YAML `parameters`) sets neither `webhookSecret` nor `webhookVerification=false`, gated on `camel-whatsapp`; the options may also be set on the component. |=== NOTE: At the time of writing Camel 4.18.6 was not on Maven Central yet; the tests that resolve 4.18.6 artifacts were run against the staging repositories of the vote (`orgapachecamel-2094`, `orgapachecamel-2095`).
