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

Update JSON type mapping with io.hypersistence:hypersistence-utils-hibernate #7

Draft
wants to merge 13 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 7 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,129 @@
/*
* Copyright 2023 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.hibernate.hibernate60;
timtebeek marked this conversation as resolved.
Show resolved Hide resolved

import lombok.EqualsAndHashCode;
import lombok.Value;
import org.openrewrite.ExecutionContext;
import org.openrewrite.Preconditions;
import org.openrewrite.Recipe;
import org.openrewrite.TreeVisitor;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.search.UsesType;
import org.openrewrite.java.tree.Expression;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.JavaType;

import java.time.Duration;
import java.util.List;
import java.util.stream.Collectors;

@Value
@EqualsAndHashCode(callSuper = true)
timtebeek marked this conversation as resolved.
Show resolved Hide resolved
public class MigrateHypersistenceUtils61Types extends Recipe {

@Override
public String getDisplayName() {
return "Migrate `io.hypersistence:hypersistence-utils-hibernate` Json type";
}

@Override
public String getDescription() {
return "When `io.hypersistence.utils` are being used, " +
"removes `@org.hibernate.annotations.TypeDefs` annotation as it doesn't exist in Hibernate 6 and updates generic JSON type mapping.";
}

@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
return Preconditions.check(
Preconditions.and(
new UsesType<>("org.hibernate.annotations.Type", true),
Preconditions.or(
new UsesType<>("com.vladmihalcea..*", true),
new UsesType<>("io.hypersistence.utils..*", true))),
new MigrateHibernateAnnotationType());
}

private static class MigrateHibernateAnnotationType extends JavaIsoVisitor<ExecutionContext> {
private static final String HIBERNATE_ANNOTATIONS_TYPE_DEF_FULLNAME = "org.hibernate.annotations.TypeDef";
private static final String HIBERNATE_ANNOTATIONS_TYPE_DEFS_FULLNAME = "org.hibernate.annotations.TypeDefs";
private static final String TYPE_DEFS_ANNOTATION = "TypeDefs";
private static final String HYPERSISTENCE_UTILS_JSON_TYPE_FULLNAME = "io.hypersistence.utils.hibernate.type.json.JsonType";
private static final String HYPERSISTENCE_UTILS_JSON_BINARY_TYPE_FULLNAME = "io.hypersistence.utils.hibernate.type.json.JsonBinaryType";
private static final String HYPERSISTENCE_UTILS_JSON_STRING_TYPE_FULLNAME = "io.hypersistence.utils.hibernate.type.json.JsonStringType";
private static final String JSON_TYPE_CLASS = "JsonType.class";

private static boolean isHibernateTypeAnnotation(J.Annotation annotation) {
return annotation.getAnnotationType() instanceof J.Identifier
&& "Type".equals(((J.Identifier) annotation.getAnnotationType()).getSimpleName())
&& annotation.getArguments() != null;
}

private static boolean isTypeJsonArgument(Expression arg) {
return arg instanceof J.Assignment
&& ((J.Assignment) arg).getVariable() instanceof J.Identifier
&& ((J.Assignment) arg).getAssignment() instanceof J.Literal
&& "type".equals(((J.Identifier) ((J.Assignment) arg).getVariable()).getSimpleName())
&& ((J.Literal) ((J.Assignment) arg).getAssignment()).getValue() != null
&& ((J.Literal) ((J.Assignment) arg).getAssignment()).getValue().toString().contains("json");
}

@Override
public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration classDecl, ExecutionContext ctx) {
J.ClassDeclaration c = super.visitClassDeclaration(classDecl, ctx);

maybeRemoveImport(HIBERNATE_ANNOTATIONS_TYPE_DEF_FULLNAME);
maybeRemoveImport(HIBERNATE_ANNOTATIONS_TYPE_DEFS_FULLNAME);

List<J.Annotation> newLeadingAnnotations = classDecl.getLeadingAnnotations().stream()
.filter(annotation -> !((J.Identifier) annotation.getAnnotationType()).getSimpleName().equals(TYPE_DEFS_ANNOTATION))
.collect(Collectors.toList());

return c.withLeadingAnnotations(newLeadingAnnotations);
}

@Override
public J.Annotation visitAnnotation(J.Annotation annotation, ExecutionContext ctx) {
// check if annotation is @org.hibernate.annotations.Type
if (isHibernateTypeAnnotation(annotation)) {
List<Expression> arguments = annotation.getArguments();
J.Annotation newAnnotation = annotation.withArguments(arguments.stream()
.map(arg -> {
if (isTypeJsonArgument(arg)) {
// import is not added when onlyIfReferenced is true because it's only used in annotation and there is no such field
maybeAddImport(HYPERSISTENCE_UTILS_JSON_TYPE_FULLNAME, false);

return ((J.Assignment) arg)
.withVariable(((J.Identifier) ((J.Assignment) arg).getVariable()).withSimpleName("value"))
.withAssignment(((J.Literal) ((J.Assignment) arg).getAssignment())
.withType(JavaType.buildType(HYPERSISTENCE_UTILS_JSON_TYPE_FULLNAME))
.withValue(JSON_TYPE_CLASS)
.withValueSource(JSON_TYPE_CLASS));
} else {
return arg;
}
})
.collect(Collectors.toList()));

maybeRemoveImport(HYPERSISTENCE_UTILS_JSON_BINARY_TYPE_FULLNAME);
maybeRemoveImport(HYPERSISTENCE_UTILS_JSON_STRING_TYPE_FULLNAME);
return newAnnotation;
}

return super.visitAnnotation(annotation, ctx);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/*
* Copyright 2023 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.
*/
@NonNullApi
@NonNullFields
package org.openrewrite.hibernate.hibernate60;

import org.openrewrite.internal.lang.NonNullApi;
import org.openrewrite.internal.lang.NonNullFields;
timtebeek marked this conversation as resolved.
Show resolved Hide resolved
timtebeek marked this conversation as resolved.
Show resolved Hide resolved
timtebeek marked this conversation as resolved.
Show resolved Hide resolved
1 change: 1 addition & 0 deletions src/main/resources/META-INF/rewrite/hibernate-6.yml
Original file line number Diff line number Diff line change
Expand Up @@ -448,3 +448,4 @@ recipeList:
oldPackageName: com.vladmihalcea
newPackageName: io.hypersistence.utils
recursive: true
- org.openrewrite.hibernate.hibernate60.MigrateHypersistenceUtils61Types
203 changes: 202 additions & 1 deletion src/test/java/org/openrewrite/hibernate/MigrateToHibernate61Test.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,10 @@

import org.junit.jupiter.api.Test;
import org.openrewrite.config.Environment;
import org.openrewrite.java.JavaParser;
import org.openrewrite.test.RecipeSpec;
import org.openrewrite.test.RewriteTest;
import org.openrewrite.test.TypeValidation;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
Expand All @@ -33,7 +35,8 @@ public void defaults(RecipeSpec spec) {
spec.recipe(Environment.builder()
.scanRuntimeClasspath("org.openrewrite.hibernate", "org.openrewrite.java.migrate.jakarta")
.build()
.activateRecipes("org.openrewrite.hibernate.MigrateToHibernate61"));
.activateRecipes("org.openrewrite.hibernate.MigrateToHibernate61"))
.parser(JavaParser.fromJavaVersion().classpath("hibernate-core", "javax.persistence-api"));
}

@Test
Expand Down Expand Up @@ -155,5 +158,203 @@ public class TestApplication {
);
}

@Test
void hypersistenceUtilsTypesMigrated() {
rewriteRun(
mavenProject(
"Sample",
//language=xml
pomXml("""
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.6.15.Final</version>
</dependency>
<dependency>
<groupId>com.vladmihalcea</groupId>
<artifactId>hibernate-types-52</artifactId>
<version>2.17.1</version>
</dependency>
</dependencies>
</project>
""", spec -> spec.after(actual -> {
Matcher hibernateMatcher = Pattern.compile("<version>(6\\.1\\.\\d+\\.Final)</version>").matcher(actual);
assertTrue(hibernateMatcher.find());
Matcher hypersistenceMatcher = Pattern.compile("<version>(3\\.5\\.\\d+)</version>").matcher(actual);
assertTrue(hypersistenceMatcher.find());
return """
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-core</artifactId>
<version>%s</version>
</dependency>
<dependency>
<groupId>io.hypersistence</groupId>
<artifactId>hypersistence-utils-hibernate-60</artifactId>
<version>%s</version>
</dependency>
</dependencies>
</project>
""".formatted(hibernateMatcher.group(1), hypersistenceMatcher.group(1));
})
),
//language=java
srcMainJava(
java("""
import com.vladmihalcea.hibernate.type.json.JsonStringType;
import org.hibernate.annotations.Type;
import org.hibernate.annotations.TypeDef;
import org.hibernate.annotations.TypeDefs;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
import java.util.Map;

@Entity
@Table(name = "schema_revisions")
@TypeDefs({@TypeDef(name = "json", typeClass = JsonStringType.class)})
public class SchemaRevisionEntity implements Serializable {
@Id
@Basic(optional = false)
@Column(name = "name", nullable = false, updatable = false)
private String name;

@Type(type = "json")
@Column(name = "schema_metadata", nullable = false)
private SchemaRevisionMetadataEntity metadata;

public static class SchemaRevisionMetadataEntity implements Serializable {
private Map<String, String> userMetadata;
}
}
""",
"""
import io.hypersistence.utils.hibernate.type.json.JsonType;
import org.hibernate.annotations.Type;

import jakarta.persistence.Basic;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import java.io.Serializable;
import java.util.Map;

@Entity
@Table(name = "schema_revisions")
public class SchemaRevisionEntity implements Serializable {
@Id
@Basic(optional = false)
@Column(name = "name", nullable = false, updatable = false)
private String name;

@Type(value = JsonType.class)
@Column(name = "schema_metadata", nullable = false)
private SchemaRevisionMetadataEntity metadata;

public static class SchemaRevisionMetadataEntity implements Serializable {
private Map<String, String> userMetadata;
}
}
"""
)
)
)
);
}

@Test
void typeDefsAnnotationIsNotRemovedWhenHypersistenceUtilsAreNotBeingUsed() {
rewriteRun(
mavenProject(
"Sample",
//language=java
srcMainJava(
java("class SomeCustomClass {}"),
java("""
import org.hibernate.annotations.Type;
import org.hibernate.annotations.TypeDef;
import org.hibernate.annotations.TypeDefs;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
import java.util.Map;

@Entity
@Table(name = "schema_revisions")
@TypeDefs({@TypeDef(name = "json", typeClass = SomeCustomClass.class)})
public class SchemaRevisionEntity implements Serializable {
@Id
@Basic(optional = false)
@Column(name = "name", nullable = false, updatable = false)
private String name;

@Column(name = "schema_metadata", nullable = false)
private SchemaRevisionMetadataEntity metadata;

public static class SchemaRevisionMetadataEntity implements Serializable {
private Map<String, String> userMetadata;
}
}
""",
"""
import org.hibernate.annotations.Type;
import org.hibernate.annotations.TypeDef;
import org.hibernate.annotations.TypeDefs;

import jakarta.persistence.Basic;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import java.io.Serializable;
import java.util.Map;

@Entity
@Table(name = "schema_revisions")
@TypeDefs({@TypeDef(name = "json", typeClass = SomeCustomClass.class)})
public class SchemaRevisionEntity implements Serializable {
@Id
@Basic(optional = false)
@Column(name = "name", nullable = false, updatable = false)
private String name;

@Column(name = "schema_metadata", nullable = false)
private SchemaRevisionMetadataEntity metadata;

public static class SchemaRevisionMetadataEntity implements Serializable {
private Map<String, String> userMetadata;
}
}
"""
)
)
)
);
}
}

Loading