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 14 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.XmlNamespaceUtils;
import org.openrewrite.xml.tree.Xml;

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

import static org.openrewrite.Tree.randomId;

@Value
@EqualsAndHashCode(callSuper = true)
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 executionContext) {
document = super.visitDocument(document, executionContext);
if (executionContext.pollMessage(MSG_TAG_UPDATED, false)) {
ammachado marked this conversation as resolved.
Show resolved Hide resolved
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);
Map<String, String> 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) {
Map<String, String> namespaces = root.getNamespaces();
if (namespaces.containsValue(newValue) && !namespaces.containsValue(XmlNamespaceUtils.XML_SCHEMA_INSTANCE_URI)) {
namespaces.put(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 @@ -15,11 +15,13 @@
*/
package org.openrewrite.xml;

import org.openrewrite.Cursor;
import org.openrewrite.internal.lang.Nullable;
import org.openrewrite.xml.tree.Content;
import org.openrewrite.xml.tree.Xml;

import java.util.List;
import java.util.Optional;

import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.toList;
Expand All @@ -46,51 +48,52 @@ private static class SemanticallyEqualVisitor extends XmlVisitor<Xml> {

@Override
public Xml visitDocument(Xml.Document document, Xml other) {
if(document == other) {
if (document == other) {
return null;
}
if(!(other instanceof Xml.Document)) {
if (!(other instanceof Xml.Document)) {
areEqual = false;
return null;
}
Xml.Document otherDocument = (Xml.Document)other;
Xml.Document otherDocument = (Xml.Document) other;
visitTag(document.getRoot(), otherDocument.getRoot());
return null;
}

@Override
public Xml visitTag(Xml.Tag tag, Xml other) {
if(tag == other) {
if (tag == other) {
return null;
}
if(!(other instanceof Xml.Tag)) {
if (!(other instanceof Xml.Tag)) {
areEqual = false;
return null;
}
Xml.Tag otherTag = (Xml.Tag)other;
if (!tag.getName().equals(otherTag.getName())) {
Xml.Tag otherTag = (Xml.Tag) other;
if (!areTagsNamesEqual(tag, otherTag, getCursor())) {
areEqual = false;
return null;
}
if(tag.getAttributes().size() != otherTag.getAttributes().size()) {
if (tag.getAttributes().size() != otherTag.getAttributes().size()) {
areEqual = false;
return null;
}
List<Xml.Attribute> theseAttributes = tag.getAttributes().stream()
.sorted(comparing(Xml.Attribute::getKeyAsString))
.sorted(comparing(Xml.Attribute::getKeyLocalName).thenComparing(a -> a.getNamespaceUri(getCursor()), comparing(Optional::get)))
.collect(toList());
List<Xml.Attribute> thoseAttributes = otherTag.getAttributes().stream()
.sorted(comparing(Xml.Attribute::getKeyAsString))
.sorted(comparing(Xml.Attribute::getKeyLocalName).thenComparing(a -> a.getNamespaceUri(getCursor()), comparing(Optional::get)))
.collect(toList());
for(int i = 0; i < theseAttributes.size(); i++) {

for (int i = 0; i < theseAttributes.size(); i++) {
visitAttribute(theseAttributes.get(i), thoseAttributes.get(i));
if(!areEqual) {
if (!areEqual) {
return null;
}
}
if(bothNullOrEmpty(tag.getContent(), otherTag.getContent())) {
if (bothNullOrEmpty(tag.getContent(), otherTag.getContent())) {
return null;
} else if(eitherNullOrEmpty(tag.getContent(), otherTag.getContent())) {
} else if (eitherNullOrEmpty(tag.getContent(), otherTag.getContent())) {
areEqual = false;
return null;
}
Expand All @@ -100,13 +103,13 @@ public Xml visitTag(Xml.Tag tag, Xml other) {
List<Content> thoseContents = otherTag.getContent().stream()
.filter(it -> it != null && !(it instanceof Xml.Comment))
.collect(toList());
if(theseContents.size() != thoseContents.size()) {
if (theseContents.size() != thoseContents.size()) {
areEqual = false;
return null;
}
for(int i = 0; i < theseContents.size(); i++) {
for (int i = 0; i < theseContents.size(); i++) {
visit(theseContents.get(i), thoseContents.get(i));
if(!areEqual) {
if (!areEqual) {
return null;
}
}
Expand All @@ -115,19 +118,19 @@ public Xml visitTag(Xml.Tag tag, Xml other) {

@Override
public Xml visitAttribute(Xml.Attribute attribute, Xml other) {
if(attribute == other) {
if (attribute == other) {
return null;
}
if(!(other instanceof Xml.Attribute)) {
if (!(other instanceof Xml.Attribute)) {
areEqual = false;
return null;
}
Xml.Attribute otherAttribute = (Xml.Attribute)other;
if(!attribute.getKeyAsString().equals(otherAttribute.getKeyAsString())) {
Xml.Attribute otherAttribute = (Xml.Attribute) other;
if (!areAttributesNamesEqual(attribute, otherAttribute, getCursor())) {
areEqual = false;
return null;
}
if(!attribute.getValueAsString().equals(otherAttribute.getValueAsString())) {
if (!attribute.getValueAsString().equals(otherAttribute.getValueAsString())) {
areEqual = false;
return null;
}
Expand All @@ -136,28 +139,42 @@ public Xml visitAttribute(Xml.Attribute attribute, Xml other) {

@Override
public Xml visitCharData(Xml.CharData charData, Xml other) {
if(charData == other) {
if (charData == other) {
return null;
}
if(!(other instanceof Xml.CharData)) {
if (!(other instanceof Xml.CharData)) {
areEqual = false;
return null;
}
Xml.CharData otherChar = (Xml.CharData)other;
if(!charData.getText().trim().equals(otherChar.getText().trim())) {
Xml.CharData otherChar = (Xml.CharData) other;
if (!charData.getText().trim().equals(otherChar.getText().trim())) {
areEqual = false;
return null;
}
return null;
}
}

private static boolean isNullOrEmpty(@Nullable List<?> a) {
return a == null || a.isEmpty();
}

private static boolean bothNullOrEmpty(@Nullable List<?> a, @Nullable List<?> b) {
return isNullOrEmpty(a) && isNullOrEmpty(b);
}

private static boolean eitherNullOrEmpty(@Nullable List<?> a, @Nullable List<?> b) {
return isNullOrEmpty(a) || isNullOrEmpty(b);
}

private static boolean areTagsNamesEqual(Xml.Tag tag, Xml.Tag other, Cursor cursor) {
return tag.getLocalName().equals(other.getLocalName()) &&
tag.getNamespaceUri(cursor).equals(other.getNamespaceUri(cursor));
}

private static boolean areAttributesNamesEqual(Xml.Attribute attribute, Xml.Attribute other, Cursor cursor) {
return attribute.getKeyLocalName().equals(other.getKeyLocalName()) &&
attribute.getValueAsString().equals(other.getValueAsString()) &&
attribute.getNamespaceUri(cursor).equals(other.getNamespaceUri(cursor));
}
}
Loading
Loading