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

Add trait to identify java package references in xml #4587

Draft
wants to merge 7 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 6 commits
Commits
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
@@ -0,0 +1,42 @@
/*
* 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;
Laurens-W marked this conversation as resolved.
Show resolved Hide resolved

import lombok.AccessLevel;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.openrewrite.xml.trait.JavaTypeReference;
import org.openrewrite.xml.trait.SpringJavaTypeReference;
import org.openrewrite.xml.tree.Xml;

import java.util.HashSet;
import java.util.Set;

@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
@Getter
public class JavaTypeReferences {
private final Xml.Document document;
private final Set<JavaTypeReference> typeReferences;

public static JavaTypeReferences build(Xml.Document doc) {
Set<JavaTypeReference> typeReferences = new HashSet<>();
new SpringJavaTypeReference.Matcher().asVisitor(reference -> {
Copy link
Contributor Author

@Laurens-W Laurens-W Oct 25, 2024

Choose a reason for hiding this comment

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

Need to figure out a way to dynamically pass a trait to use here

typeReferences.add(reference);
return reference.getTree();
}).visit(doc, null);
return new JavaTypeReferences(doc, typeReferences);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package org.openrewrite.xml.trait;
Laurens-W marked this conversation as resolved.
Show resolved Hide resolved

import org.jspecify.annotations.Nullable;
import org.openrewrite.Tree;
import org.openrewrite.trait.Trait;

public interface JavaTypeReference extends Trait<Tree> {

@Nullable String getValue();

}
Copy link
Contributor Author

Choose a reason for hiding this comment

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

This should be moved to rewrite-spring

Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/*
* 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.trait;

import lombok.Value;
import org.jspecify.annotations.Nullable;
import org.openrewrite.Cursor;
import org.openrewrite.Tree;
import org.openrewrite.trait.SimpleTraitMatcher;
import org.openrewrite.trait.Trait;
import org.openrewrite.xml.XPathMatcher;
import org.openrewrite.xml.tree.Xml;

import java.util.regex.Pattern;

@Value
public class SpringJavaTypeReference implements JavaTypeReference {
Cursor cursor;

@Override
public @Nullable String getValue() {
if (getTree() instanceof Xml.Attribute) {
Xml.Attribute attribute = (Xml.Attribute) getTree();
return attribute.getValueAsString();
} else if (getTree() instanceof Xml.Tag) {
Xml.Tag tag = (Xml.Tag) getTree();
if (tag.getValue().isPresent()) {
return tag.getValue().get();
}
}
return null;
}

public static class Matcher extends SimpleTraitMatcher<SpringJavaTypeReference> {
private final Pattern typeReference = Pattern.compile("(?:[a-zA-Z_][a-zA-Z0-9_]*\\.)+[A-Z*][a-zA-Z0-9_]*(?:<[a-zA-Z0-9_,?<> ]*>)?");
private final XPathMatcher classXPath = new XPathMatcher("//@class");
private final XPathMatcher typeXPath = new XPathMatcher("//@type");
private final XPathMatcher tags = new XPathMatcher("//value");

@Override
protected @Nullable SpringJavaTypeReference test(Cursor cursor) {
Object value = cursor.getValue();
if (value instanceof Xml.Attribute) {
Xml.Attribute attrib = (Xml.Attribute) value;
if (classXPath.matches(cursor) || typeXPath.matches(cursor)) {
if (typeReference.matcher(attrib.getValueAsString()).matches()) {
return new SpringJavaTypeReference(cursor);
}
}
} else if (value instanceof Xml.Tag) {
Xml.Tag tag = (Xml.Tag) value;
if (tags.matches(cursor)) {
if (tag.getValue().isPresent() && typeReference.matcher(tag.getValue().get()).matches()) {
return new SpringJavaTypeReference(cursor);
}
}
}
return null;
}
}
}
37 changes: 32 additions & 5 deletions rewrite-xml/src/main/java/org/openrewrite/xml/tree/Xml.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import com.fasterxml.jackson.annotation.JsonCreator;
import lombok.*;
import lombok.experimental.FieldDefaults;
import lombok.experimental.NonFinal;
import org.apache.commons.text.StringEscapeUtils;
import org.intellij.lang.annotations.Language;
import org.jspecify.annotations.Nullable;
Expand All @@ -26,10 +27,13 @@
import org.openrewrite.marker.Markers;
import org.openrewrite.xml.XmlParser;
import org.openrewrite.xml.XmlVisitor;
import org.openrewrite.xml.internal.JavaTypeReferences;
import org.openrewrite.xml.internal.WithPrefix;
import org.openrewrite.xml.internal.XmlPrinter;
import org.openrewrite.xml.internal.XmlWhitespaceValidationService;

import java.beans.Transient;
import java.lang.ref.SoftReference;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
Expand Down Expand Up @@ -79,6 +83,7 @@ default <P> boolean isAcceptable(TreeVisitor<?, P> v, P p) {
@FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE)
@EqualsAndHashCode(callSuper = false, onlyExplicitlyIncluded = true)
@RequiredArgsConstructor
@AllArgsConstructor(access = AccessLevel.PRIVATE)
class Document implements Xml, SourceFile {
@With
@EqualsAndHashCode.Include
Expand Down Expand Up @@ -141,7 +146,7 @@ public Document withEof(String eof) {
if (this.eof.equals(eof)) {
return this;
}
return new Document(id, sourcePath, prefixUnsafe, markers, charsetName, charsetBomMarked, checksum, fileAttributes, prolog, root, eof);
return new Document(id, sourcePath, prefixUnsafe, markers, charsetName, charsetBomMarked, checksum, fileAttributes, prolog, root, eof, javaTypeReferences);
}

@Override
Expand All @@ -162,6 +167,27 @@ public <S, T extends S> T service(Class<S> service) {
}
return SourceFile.super.service(service);
}

@Nullable
@NonFinal
SoftReference<JavaTypeReferences> javaTypeReferences;

@Transient
public JavaTypeReferences getJavaTypeReferences() {
JavaTypeReferences cache;
if (this.javaTypeReferences == null) {
cache = JavaTypeReferences.build(this);
this.javaTypeReferences = new SoftReference<>(cache);
} else {
cache = this.javaTypeReferences.get();
if (cache == null || cache.getDocument() != this) {
cache = JavaTypeReferences.build(this);
this.javaTypeReferences = new SoftReference<>(cache);
}
}
return cache;
}

}

@Value
Expand Down Expand Up @@ -304,10 +330,10 @@ public static Xml.Tag build(@Language("xml") String tagSource) {
}

public Tag withName(String name) {
if(!name.equals(name.trim())) {
if (!name.equals(name.trim())) {
throw new IllegalArgumentException("Tag name must not contain leading or trailing whitespace");
}
if(this.name.equals(name)) {
if (this.name.equals(name)) {
return this;
}
return new Tag(id, prefixUnsafe, markers, name, attributes, content,
Expand Down Expand Up @@ -654,7 +680,7 @@ public String toString() {

@Value
@EqualsAndHashCode(callSuper = false, onlyExplicitlyIncluded = true)
@AllArgsConstructor(onConstructor_ = { @JsonCreator })
@AllArgsConstructor(onConstructor_ = {@JsonCreator})
@With
class DocTypeDecl implements Xml, Misc {
@EqualsAndHashCode.Include
Expand All @@ -675,10 +701,11 @@ public String getPrefix() {
Markers markers;
Ident name;
String documentDeclaration;

// Override lombok default getter to avoid backwards compatibility problems with old LSTs
public String getDocumentDeclaration() {
//noinspection ConstantValue
if ( documentDeclaration == null) {
if (documentDeclaration == null) {
return "DOCTYPE";
}
return documentDeclaration;
Expand Down
28 changes: 28 additions & 0 deletions rewrite-xml/src/test/java/org/openrewrite/xml/XmlParserTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,34 @@ void parseXmlDocument() {
);
}

@Test
void javaTypeReferenceDocument() {
rewriteRun(
xml(
"""
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="testBean" class="org.springframework.beans.TestBean" scope="prototype">
<property name="age" value="10"/>
<property name="sibling">
<bean class="org.springframework.beans.TestBean">
<property name="age" value="11" class="java.lang.Integer"/>
<property name="someName">
<value>java.lang.String</value>
</property>
</bean>
</property>
</bean>
</beans>
""",
spec -> spec.afterRecipe(doc -> {
assertThat(doc.getJavaTypeReferences().getTypeReferences().stream().anyMatch(typeRef -> typeRef.getValue().equals("java.lang.String")));
})
)
);
}

@Issue("https://github.com/openrewrite/rewrite/issues/2290")
@Test
void cdataTagWhitespace() {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
/*
* 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.trait;

import org.junit.jupiter.api.Test;
import org.openrewrite.DocumentExample;
import org.openrewrite.marker.SearchResult;
import org.openrewrite.test.RecipeSpec;
import org.openrewrite.test.RewriteTest;

import static org.openrewrite.xml.Assertions.xml;

class SpringJavaTypeReferenceTest implements RewriteTest {

@Override
public void defaults(RecipeSpec spec) {
spec.recipe(RewriteTest.toRecipe(() -> new SpringJavaTypeReference.Matcher()
.asVisitor(springJavaTypeReference -> SearchResult.found(springJavaTypeReference.getTree(), springJavaTypeReference.getValue()))));
}

@SuppressWarnings("SpringXmlModelInspection")
@Test
@DocumentExample
void xmlConfiguration() {
rewriteRun(
xml(
//language=xml
"""
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="testBean" class="org.springframework.beans.TestBean" scope="prototype">
<property name="age" value="10"/>
<property name="sibling">
<bean class="org.springframework.beans.TestBean">
<property name="age" value="11" class="java.lang.Integer"/>
<property name="someName">
<value>java.lang.String</value>
</property>
</bean>
</property>
</bean>
</beans>
""",
//language=xml
"""
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="testBean" <!--~~(org.springframework.beans.TestBean)~~>-->class="org.springframework.beans.TestBean" scope="prototype">
<property name="age" value="10"/>
<property name="sibling">
<bean <!--~~(org.springframework.beans.TestBean)~~>-->class="org.springframework.beans.TestBean">
<property name="age" value="11" <!--~~(java.lang.Integer)~~>-->class="java.lang.Integer"/>
<property name="someName">
<!--~~(java.lang.String)~~>--><value>java.lang.String</value>
</property>
</bean>
</property>
</bean>
</beans>
"""
)
);
}
}
Loading