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

Remove Temporal annotation from attributes to avoid EclipseLink error #420

Merged
merged 10 commits into from
Apr 24, 2024
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
/*
* 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.java.migrate.javax;

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.RemoveAnnotation;
import org.openrewrite.java.search.FindAnnotations;
import org.openrewrite.java.search.UsesType;
import org.openrewrite.java.tree.J;

import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Value
@EqualsAndHashCode(callSuper = false)
public class RemoveTemporalAnnotation extends Recipe {
/*
* This rule scans for the following annotation-attribute combinations where data does not need to be converted
* and the Temporal annotation must be removed to avoid an EclipseLink error:
*
* A javax.persistence.Temporal(TemporalType.DATE) annotation on a java.sql.Date attribute
* A the javax.persistence.Temporal(TemporalType.TIME) annotation on a java.sql.Date attribute
* A the javax.persistence.Temporal(TemporalType.DATE) annotation on a java.sql.Time attribute
* A the javax.persistence.Temporal(TemporalType.TIME) annotation on a java.sql.Time attribute
* A the javax.persistence.Temporal(TemporalType.TIMESTAMP) annotation on a java.sql.Time
* A the javax.persistence.Temporal(TemporalType.TIMESTAMP) annotation on a java.sql.Timestamp attribute
*
* NOTES: @Temporal has a required argument, which can only be TemporalType.DATE/TIME/TIMESTAMP
*/

@Override
public String getDisplayName() {
return "Remove the `@Temporal` annotation for some `java.sql` attributes";
}

@Override
public String getDescription() {
return "OpenJPA persists the fields of attributes of type `java.sql.Date`, `java.sql.Time`, or `java.sql.Timestamp` " +
"that have a `javax.persistence.Temporal` annotation, whereas EclipseLink throws an exception. " +
"Remove the `@Temporal` annotation so the behavior in EclipseLink will match the behavior in OpenJPA.";
}

@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
Pattern temporalPattern = Pattern.compile(".*TemporalType\\.(TIMESTAMP|DATE|TIME)");
final String JAVA_SQL_TIMESTAMP = "java.sql.Timestamp";
final String JAVA_SQL_TIME = "java.sql.Time";
final String JAVA_SQL_DATE = "java.sql.Date";

Set<String> javaSqlDateTimeTypes = Stream.of(
JAVA_SQL_TIMESTAMP,
JAVA_SQL_TIME,
JAVA_SQL_DATE
).collect(Collectors.toSet());
// Combinations of TemporalType and java.sql classes that do not need removal
Map<String, String> doNotRemove = Stream.of(new String[][]{
{"DATE", JAVA_SQL_TIMESTAMP},
{"TIME", JAVA_SQL_TIMESTAMP},
{"TIMESTAMP", JAVA_SQL_DATE}
}).collect(Collectors.toMap(data -> data[0], data -> data[1]));
// TODO: maybe future recipe to handle these by creating a converter class
// https://wiki.eclipse.org/EclipseLink/Examples/JPA/Migration/OpenJPA/Mappings#.40Temporal_on_java.sql.Date.2FTime.2FTimestamp_fields

return Preconditions.check(
Preconditions.and(
new UsesType<>("javax.persistence.Temporal", true),
Preconditions.or(
new UsesType<>(JAVA_SQL_DATE, true),
new UsesType<>(JAVA_SQL_TIME, true),
new UsesType<>(JAVA_SQL_TIMESTAMP, true)
)
),
new JavaIsoVisitor<ExecutionContext>() {
@Override
public J.VariableDeclarations visitVariableDeclarations(J.VariableDeclarations multiVariable, ExecutionContext ctx) {
// Exit if no @Temporal annotation, or var is not java.sql.Date/Time/Timestamp
String varClass = multiVariable.getType().toString();
Set<J.Annotation> temporalAnnos = FindAnnotations.find(multiVariable, "javax.persistence.Temporal");
if (temporalAnnos.isEmpty() || !javaSqlDateTimeTypes.contains(varClass)) {
return multiVariable;
}

// Get TemporalType
J.Annotation temporal = temporalAnnos.iterator().next();
String temporalArg = temporal.getArguments().iterator().next().toString();
Matcher temporalMatch = temporalPattern.matcher(temporalArg);
if (!temporalMatch.find()) {
return multiVariable;
}
String temporalType = temporalMatch.group(1);

// Check combination of attribute and var's class
if (doNotRemove.get(temporalType).equals(varClass)) {
return multiVariable;
}

// Remove @Temporal annotation
return (J.VariableDeclarations) new RemoveAnnotation("javax.persistence.Temporal").getVisitor().visit(multiVariable, ctx);
}
}
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,6 @@ recipeList:
- org.openrewrite.java.migrate.javax.AddColumnAnnotation
- org.openrewrite.java.migrate.javax.AddDefaultConstructorToEntityClass
- org.openrewrite.java.migrate.javax.RemoveEmbeddableId
- org.openrewrite.java.migrate.javax.RemoveTemporalAnnotation
- org.openrewrite.java.migrate.javax.UseJoinColumnForMapping

Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
/*
* 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.java.migrate.javax;

import org.junit.jupiter.api.Test;
import org.openrewrite.DocumentExample;
import org.openrewrite.InMemoryExecutionContext;
import org.openrewrite.java.JavaParser;
import org.openrewrite.test.RecipeSpec;
import org.openrewrite.test.RewriteTest;

import static org.openrewrite.java.Assertions.java;

class RemoveTemporalAnnotationTest implements RewriteTest {
@Override
public void defaults(RecipeSpec spec) {
spec.parser(JavaParser.fromJavaVersion().classpathFromResources(new InMemoryExecutionContext(), "javax.persistence-api-2.2"))
.recipe(new RemoveTemporalAnnotation());
}

@Test
@DocumentExample
void removeTemporalAnnotation() {
//language=java
rewriteRun(
java(
"""
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;

public class TemporalDates {
Copy link
Contributor

Choose a reason for hiding this comment

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

Can you port over the following fields:

  • TemporalType.TIMESTAMP used with java.sql.Date
  • TemporalType.DATE used with java.sql.Timestamp
  • TemporalType.TIME used with java.sql.Timestamp

Copy link
Contributor

Choose a reason for hiding this comment

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

Actually I think the help we have for this issue is incorrect. It sounds like this recipes only needs to remove annotation for the following combinations:

  • TemporalType.TIMESTAMP and java.sql.Timestamp
  • TemporalType.DATE and java.sql.Date
  • TemporalType.TIME and java.sql.Time

Screenshot 2024-03-07 at 3 27 24 PM

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I did notice the rule is overly broad, but the other cases that we remove the annotation would have been an invalid combination in either OpenJPA or EclipseLink anyway. So it would just fix the code error.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

For clarity, the current implementation handles/fixes all the cases except the ones that require a converter.
Do we want to include the converter in this recipe?

Copy link
Contributor

Choose a reason for hiding this comment

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

Let's not worry about the converter for now. But I'll create an issue to look into it later.

@Temporal(TemporalType.DATE)
private Date dateDate;

@Temporal(TemporalType.TIME)
private Date dateTime;

@Temporal(TemporalType.DATE)
private Time timeDate;

@Temporal(TemporalType.TIME)
private java.sql.Time timeTime;

@Temporal(TemporalType.TIMESTAMP)
private java.sql.Time timeTimestamp;

@Temporal(TemporalType.TIMESTAMP)
private java.sql.Timestamp timestampTimestamp;
}
""",
"""
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;

public class TemporalDates {
private Date dateDate;

private Date dateTime;

private Time timeDate;

private java.sql.Time timeTime;

private java.sql.Time timeTimestamp;

private java.sql.Timestamp timestampTimestamp;
}
"""
)
);
}

Copy link
Contributor

Choose a reason for hiding this comment

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

It probably makes sense to have a test that uses Date, Time, and Timestamp classes from other packages such as java.util.Date, java.security.Timestamp, org.omg.Security.Time to make it clear those are valid cases

Copy link
Contributor Author

Choose a reason for hiding this comment

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

From the Eclipse page, I only see that java.util.Date and java.util.Calendar are allowed. I added a test case with these to show no change occurs.

Copy link
Contributor

@cjobinabo cjobinabo Apr 24, 2024

Choose a reason for hiding this comment

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

Yeah the idea behind the tests using Date, Time, and Timestamp classes from other packages was to make it clear the recipe should only apply to java.sql.Date, java.sql.Timestamp, java.sql.Time. I see I had a typo in my original comment.

Update:
It looks like your allowTemporalOnValidClasses test covers this

@Test
void dontChangeOtherCombinations() {
// These combinations require a converter
//language=java
rewriteRun(
java(
"""
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;

public class TemporalDates {
@Temporal(TemporalType.TIMESTAMP)
private Date dateDate;

@Temporal(TemporalType.DATE)
private java.sql.Timestamp timestampTimestamp;

@Temporal(TemporalType.TIME)
private java.sql.Timestamp timestampTimestamp;
}
"""
)
);
}

@Test
void allowTemporalOnValidClasses() {
//language=java
rewriteRun(
java(
"""
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import java.util.Date;
import java.util.Calendar;

public class TemporalDates {
@Temporal(TemporalType.TIMESTAMP)
private Date dateDate;

@Temporal(TemporalType.DATE)
private Calendar timestampTimestamp;
}
"""
)
);
}
}