Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Partial support for parsing XML namespaces #3925

Merged
merged 32 commits into from
Jun 20, 2024
Merged
Show file tree
Hide file tree
Changes from 23 commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
512d05e
Partial support for parsing XML namespaces
ammachado Jan 16, 2024
7b65a68
Adding namespace resolution
ammachado Jan 16, 2024
9d4c924
Missing license header
ammachado Jan 16, 2024
520a282
Adding recipes to search namespace URIs/prefixes
ammachado Jan 16, 2024
1ec44eb
Namespace shortcut methods on \'Xml.Document\'
ammachado Jan 16, 2024
f5a3621
Change implementation to rely only on attributes
ammachado Jan 16, 2024
aecc3e6
Javadocs and cleanup
ammachado Jan 16, 2024
385cb7b
Rename XmlNamespaceUtils & minor polish
timtebeek Jan 16, 2024
c88e2ae
Fix namespace search on XML hierarchy
ammachado Jan 17, 2024
546b99f
`ChangeNamespaceValue` now updates the `schemaLocation` attribute
ammachado Jan 17, 2024
5d2e2b8
Merge branch 'main' into add-namespaces-xml-tree
ammachado Jan 17, 2024
e0e9527
Merge branch 'main' into add-namespaces-xml-tree
timtebeek Jan 17, 2024
436049d
Merge branch 'main' into add-namespaces-xml-tree
ammachado Jan 27, 2024
f621398
Consider namespaces on `SemanticallyEqual`.
ammachado Jan 27, 2024
218827b
Suggestions from code review.
ammachado Jan 27, 2024
a456198
Update rewrite-xml/src/main/java/org/openrewrite/xml/ChangeNamespaceV…
ammachado Jan 28, 2024
b283aa0
Revert namespace comparison changes in `SemanticallyEqual`.
ammachado Feb 2, 2024
5c76231
Merge branch 'main' into add-namespaces-xml-tree
ammachado Feb 2, 2024
d1cffc1
Merge branch 'main' into add-namespaces-xml-tree
timtebeek Feb 20, 2024
acb7c26
Merge branch 'main' into add-namespaces-xml-tree
ammachado Feb 24, 2024
6fec0b5
Merge branch 'main' into add-namespaces-xml-tree
timtebeek Feb 24, 2024
bf3b658
Adding a Namespaces abstraction
ammachado Feb 27, 2024
ac084a1
Merge branch 'main' into add-namespaces-xml-tree
evie-lau Jun 4, 2024
326b824
Add support for wildcard and local-name()
evie-lau Jun 13, 2024
50dc26f
Merge branch 'main' into add-namespaces-xml-tree
evie-lau Jun 14, 2024
20e6212
Apply suggestions from code review
timtebeek Jun 14, 2024
69d6772
Fix `Namespaces` mutability
ammachado Jun 14, 2024
527a239
Merge branch 'main' into add-namespaces-xml-tree
timtebeek Jun 14, 2024
2a0212b
Adding an iterator implementation for `Namespaces`
ammachado Jun 14, 2024
cd2fcf3
Replace `NotNull` with OpenRewrite's `NonNull`
ammachado Jun 14, 2024
c7f84cc
Merge branch 'main' into add-namespaces-xml-tree
sambsnyd Jun 20, 2024
e4083b4
Polish.
sambsnyd Jun 20, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,27 @@
import lombok.Value;
import org.openrewrite.*;
import org.openrewrite.internal.ListUtils;
import org.openrewrite.internal.StringUtils;
import org.openrewrite.internal.lang.Nullable;
import org.openrewrite.marker.Markers;
import org.openrewrite.xml.internal.Namespaces;
import org.openrewrite.xml.internal.XmlNamespaceUtils;
import org.openrewrite.xml.tree.Xml;

import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static org.openrewrite.Tree.randomId;

@Value
@EqualsAndHashCode(callSuper = false)
public class ChangeNamespaceValue extends Recipe {
private static final String XMLNS_PREFIX = "xmlns";
private static final String VERSION_PREFIX = "version";
private static final String SCHEMA_LOCATION_MATCH_PATTERN = "(?m)(.*)(%s)(\\s+)(.*)";
private static final String SCHEMA_LOCATION_REPLACEMENT_PATTERN = "$1%s$3%s";
private static final String MSG_TAG_UPDATED = "msg-tag-updated";

@Override
public String getDisplayName() {
Expand Down Expand Up @@ -71,16 +84,40 @@ public String getDescription() {
required = false)
Boolean searchAllNamespaces;

@Nullable
@Option(displayName = "New Resource version",
description = "The new version of the resource",
example = "2.0")
String newVersion;

@Option(displayName = "Schema Location",
description = "The new value to be used for the namespace schema location.",
example = "newfoo.bar.attribute.value.string",
required = false)
@Nullable
String newSchemaLocation;

@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
XPathMatcher elementNameMatcher = elementName != null ? new XPathMatcher(elementName) : null;
return new XmlIsoVisitor<ExecutionContext>() {
@Override
public Xml.Document visitDocument(Xml.Document document, ExecutionContext ctx) {
document = super.visitDocument(document, ctx);
if (ctx.pollMessage(MSG_TAG_UPDATED, false)) {
document = document.withRoot(addOrUpdateSchemaLocation(document.getRoot(), getCursor()));
}
return document;
}

@Override
public Xml.Tag visitTag(Xml.Tag tag, ExecutionContext ctx) {
Xml.Tag t = super.visitTag(tag, ctx);

if (matchesElementName(getCursor()) && matchesVersion(t)) {
t = t.withAttributes(ListUtils.map(t.getAttributes(), this::maybeReplaceNamespaceAttribute));
t = t.withAttributes(ListUtils.map(t.getAttributes(), this::maybeReplaceVersionAttribute));
ctx.putMessage(MSG_TAG_UPDATED, true);
}

return t;
Expand Down Expand Up @@ -114,6 +151,18 @@ private Xml.Attribute maybeReplaceNamespaceAttribute(Xml.Attribute attribute) {
return attribute;
}

private Xml.Attribute maybeReplaceVersionAttribute(Xml.Attribute attribute) {
if (isVersionAttribute(attribute) && newVersion != null) {
return attribute.withValue(
new Xml.Attribute.Value(attribute.getId(),
"",
attribute.getMarkers(),
attribute.getValue().getQuote(),
newVersion));
}
return attribute;
}

private boolean isXmlnsAttribute(Xml.Attribute attribute) {
boolean searchAll = searchAllNamespaces == null || Boolean.TRUE.equals(searchAllNamespaces);
return searchAll && attribute.getKeyAsString().startsWith(XMLNS_PREFIX) ||
Expand Down Expand Up @@ -149,6 +198,80 @@ private boolean isVersionMatch(Xml.Attribute attribute) {
}
return false;
}

private Xml.Tag addOrUpdateSchemaLocation(Xml.Tag root, Cursor cursor) {
if (StringUtils.isBlank(newSchemaLocation)) {
return root;
}
Xml.Tag newRoot = maybeAddNamespace(root);
Optional<Xml.Attribute> maybeSchemaLocation = maybeGetSchemaLocation(cursor, newRoot);
if (maybeSchemaLocation.isPresent() && oldValue != null) {
newRoot = updateSchemaLocation(newRoot, maybeSchemaLocation.get());
} else if (!maybeSchemaLocation.isPresent()) {
newRoot = addSchemaLocation(newRoot);
}
return newRoot;
}

private Optional<Xml.Attribute> maybeGetSchemaLocation(Cursor cursor, Xml.Tag tag) {
Xml.Tag schemaLocationTag = XmlNamespaceUtils.findTagContainingXmlSchemaInstanceNamespace(cursor, tag);
Namespaces namespaces = tag.getNamespaces();
return schemaLocationTag.getAttributes().stream().filter(attribute -> {
String attributeNamespace = namespaces.get(XmlNamespaceUtils.extractNamespacePrefix(attribute.getKeyAsString()));
return XmlNamespaceUtils.XML_SCHEMA_INSTANCE_URI.equals(attributeNamespace)
&& attribute.getKeyAsString().endsWith("schemaLocation");
}).findFirst();
}

private Xml.Tag maybeAddNamespace(Xml.Tag root) {
Namespaces namespaces = root.getNamespaces();
if (namespaces.containsUri(newValue) && !namespaces.containsUri(XmlNamespaceUtils.XML_SCHEMA_INSTANCE_URI)) {
namespaces.add(XmlNamespaceUtils.XML_SCHEMA_INSTANCE_PREFIX, XmlNamespaceUtils.XML_SCHEMA_INSTANCE_URI);
root = root.withNamespaces(namespaces);
}
return root;
}

private Xml.Tag updateSchemaLocation(Xml.Tag newRoot, Xml.Attribute attribute) {
String oldSchemaLocation = attribute.getValueAsString();
Matcher pattern = Pattern.compile(String.format(SCHEMA_LOCATION_MATCH_PATTERN, Pattern.quote(oldValue)))
.matcher(oldSchemaLocation);
if (pattern.find()) {
String newSchemaLocationValue = pattern.replaceFirst(
String.format(SCHEMA_LOCATION_REPLACEMENT_PATTERN, newValue, newSchemaLocation)
);
Xml.Attribute newAttribute = attribute.withValue(attribute.getValue().withValue(newSchemaLocationValue));
newRoot = newRoot.withAttributes(ListUtils.map(newRoot.getAttributes(), a -> a == attribute ? newAttribute : a));
}
return newRoot;
}

private Xml.Tag addSchemaLocation(Xml.Tag newRoot) {
return newRoot.withAttributes(
ListUtils.concat(
newRoot.getAttributes(),
new Xml.Attribute(
randomId(),
" ",
Markers.EMPTY,
new Xml.Ident(
randomId(),
"",
Markers.EMPTY,
String.format("%s:schemaLocation", XmlNamespaceUtils.XML_SCHEMA_INSTANCE_PREFIX)
),
"",
new Xml.Attribute.Value(
randomId(),
"",
Markers.EMPTY,
Xml.Attribute.Value.Quote.Double,
String.format("%s %s", newValue, newSchemaLocation)
)
)
)
);
}
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import org.openrewrite.Cursor;
import org.openrewrite.internal.StringUtils;
import org.openrewrite.internal.lang.Nullable;
import org.openrewrite.xml.internal.Namespaces;
import org.openrewrite.xml.search.FindTags;
import org.openrewrite.xml.tree.Xml;

Expand All @@ -40,12 +41,18 @@ public class XPathMatcher {
private static final Pattern PATTERN = Pattern.compile("([-\\w]+)\\[(@)?([-\\w]+)='([-\\w.]+)']");

private final String expression;
private final Namespaces namespaces;
private final boolean startsWithSlash;
private final boolean startsWithDoubleSlash;
private final String[] parts;

public XPathMatcher(String expression) {
this(expression, new Namespaces());
}

public XPathMatcher(String expression, Namespaces namespaces) {
this.expression = expression;
this.namespaces = namespaces;
startsWithSlash = expression.startsWith("/");
startsWithDoubleSlash = expression.startsWith("//");
parts = expression.substring(startsWithDoubleSlash ? 2 : startsWithSlash ? 1 : 0).split("/");
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/*
* Copyright 2024 the original author or authors.
* <p>
* Licensed 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.openrewrite.xml.internal;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since this is returned from tree.Xml perhaps we should not have this class in an internal package?


import lombok.Value;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Value
public class Namespaces {

Map<String, String> namespaces = new HashMap<>();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A mutable map here might lead to problems with our immutability convention and detecting changes.


public Namespaces() {
}

public Namespaces(String prefix, String uri) {
add(prefix, uri);
}

public Namespaces add(String prefix, String uri) {
namespaces.put(prefix, uri);
return this;
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Namespaces should be immutable like other parts of the LST


public Namespaces combine(Namespaces namespaces) {
this.namespaces.putAll(namespaces.getNamespaces());
return this;
}

public String get(String prefix) {
return namespaces.get(prefix);
}

public boolean containsPrefix(String prefix) {
return namespaces.containsKey(prefix);
}

public boolean containsUri(String uri) {
return namespaces.containsValue(uri);
}

public Set<Map.Entry<String, String>> entrySet() {
return namespaces.entrySet();
}
}
Loading