### Java Code Migration Example: Java 8-16 to Java 17 Source: https://context7.com/openrewrite/rewrite-migrate-java/llms.txt Demonstrates Java code transformations before and after applying the UpgradeToJava17 recipe. It shows changes for deprecated methods, API namespaces (javax to jakarta), and the introduction of text blocks. ```java // Before migration public class Example { public static void main(String[] args) { Thread.countStackFrames(); // Deprecated, removed in Java 14 javax.tools.ToolProvider provider = new javax.tools.ToolProvider(); var compiler = provider.getSystemJavaCompiler(); // Constructor removed String multiline = "First line\n" + "Second line\n" + "Third line"; } } // After migration public class Example { public static void main(String[] args) { // Method invocation removed var compiler = javax.tools.ToolProvider.getSystemJavaCompiler(); // Static method String multiline = """ First line Second line Third line"""; // Text blocks } } ``` -------------------------------- ### Java Code Migration Example: Java 21 Features Source: https://context7.com/openrewrite/rewrite-migrate-java/llms.txt Illustrates Java code modernization for Java 21, showcasing the transition from traditional collection access to sequenced collections (e.g., getFirst(), getLast()) and the use of pattern matching in switch expressions. ```java // Before: Old collection patterns List items = Arrays.asList("a", "b", "c"); String first = items.get(0); String last = items.get(items.size() - 1); // After: Sequenced collections (Java 21) List items = Arrays.asList("a", "b", "c"); String first = items.getFirst(); String last = items.getLast(); // Before: Switch statements String result; switch (obj) { case String s: result = s.toUpperCase(); break; case Integer i: result = String.valueOf(i); break; default: result = "unknown"; } // After: Switch expressions with pattern matching String result = switch (obj) { case String s -> s.toUpperCase(); case Integer i -> String.valueOf(i); default -> "unknown"; }; ``` -------------------------------- ### Configure Java 21 Migration Recipe in rewrite.yml Source: https://context7.com/openrewrite/rewrite-migrate-java/llms.txt Example YAML configuration for a custom Java 21 migration recipe using OpenRewrite. This includes the core UpgradeToJava21 recipe and CommonStaticAnalysis for broader code modernization. ```yaml --- type: specs.openrewrite.org/v1beta/recipe name: com.example.CustomJava21Migration displayName: Custom Java 21 Migration recipeList: - org.openrewrite.java.migrate.UpgradeToJava21 - org.openrewrite.staticanalysis.CommonStaticAnalysis ``` -------------------------------- ### Add JAXB Runtime Dependencies for Java 11+ Source: https://context7.com/openrewrite/rewrite-migrate-java/llms.txt This example shows how to automatically add the JAXB runtime dependency for projects using Java 11 or later, where JAXB was removed from the standard JDK. It includes the Maven XML dependency declaration. ```xml javax.xml.bind jaxb-api 2.3.1 org.glassfish.jaxb jaxb-runtime 2.3.9 runtime ``` -------------------------------- ### JAXB Usage in Java Source Code Source: https://context7.com/openrewrite/rewrite-migrate-java/llms.txt This Java code snippet demonstrates the usage of JAXB for XML marshalling and unmarshalling. It remains unchanged by the JAXB dependency migration but serves as an example of code that might trigger the need for the dependency. ```java // Source code using JAXB (unchanged) import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import javax.xml.bind.annotation.*; @XmlRootElement public class Person { @XmlElement private String name; public static void main(String[] args) throws Exception { JAXBContext context = JAXBContext.newInstance(Person.class); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); Person person = new Person(); person.name = "John"; marshaller.marshal(person, System.out); } } ``` -------------------------------- ### Run Maven/Gradle to Upgrade Java to Java 17 Source: https://context7.com/openrewrite/rewrite-migrate-java/llms.txt Commands to execute the OpenRewrite migration to Java 17 using Maven or Gradle. This recipe handles dependency updates, deprecated API replacements, and module system compliance. ```maven mvn org.openrewrite.maven:rewrite-maven-plugin:run \ -Drewrite.activeRecipes=org.openrewrite.java.migrate.UpgradeToJava17 ``` ```gradle ./gradlew rewriteRun -Drewrite.activeRecipes=org.openrewrite.java.migrate.UpgradeToJava17 ``` -------------------------------- ### Define Company Migration Plan with Custom Recipes Source: https://context7.com/openrewrite/rewrite-migrate-java/llms.txt This Java code shows how to define a comprehensive migration plan in OpenRewrite by combining standard OpenRewrite recipes with custom-developed recipes. It illustrates including Java version upgrades, custom transformations, and formatting. ```java // Usage in custom recipe list package com.example; import org.openrewrite.*; import java.util.*; public class CompanyMigrationPlan extends Recipe { @Override public String getDisplayName() { return "Company Java 17 Migration Plan"; } @Override public List getRecipeList() { return Arrays.asList( // Standard OpenRewrite migrations new org.openrewrite.java.migrate.UpgradeToJava17(), // Custom company-specific migrations new MigrateLegacyLogger(), new UpdateProprietaryFramework(), new RemoveDeprecatedInternalAPIs(), // Post-migration cleanup new org.openrewrite.staticanalysis.CommonStaticAnalysis(), new org.openrewrite.java.format.AutoFormat() ); } } ``` -------------------------------- ### Replace Guava Collections and Optional with Java Standard Library Source: https://context7.com/openrewrite/rewrite-migrate-java/llms.txt This snippet demonstrates replacing Guava's collection utilities (Lists, Sets, Maps, Immutable collections) and Optional with their equivalent Java standard library classes. It also shows the replacement of Guava's Joiner. ```java // Before: Guava collections import com.google.common.collect.*; List list = Lists.newArrayList("a", "b", "c"); Set set = Sets.newHashSet(1, 2, 3); Map map = Maps.newHashMap(); ImmutableList immutable = ImmutableList.of("x", "y", "z"); ImmutableSet immutableSet = ImmutableSet.of("a", "b"); ImmutableMap immutableMap = ImmutableMap.of("key", 1); Optional guavaOpt = com.google.common.base.Optional.of("value"); String joined = Joiner.on(",").join(Arrays.asList("a", "b", "c")); // After: Java standard library import java.util.*; List list = new ArrayList<>(Arrays.asList("a", "b", "c")); Set set = new HashSet<>(Arrays.asList(1, 2, 3)); Map map = new HashMap<>(); List immutable = List.of("x", "y", "z"); Set immutableSet = Set.of("a", "b"); Map immutableMap = Map.of("key", 1); Optional opt = Optional.of("value"); String joined = String.join(",", Arrays.asList("a", "b", "c")); ``` -------------------------------- ### Migrate Java EE 8 to Jakarta EE 10 Source: https://context7.com/openrewrite/rewrite-migrate-java/llms.txt This recipe transforms Java EE 8 applications to Jakarta EE 10 by updating namespaces and APIs. It requires adding the rewrite-maven-plugin to your `pom.xml` and specifying the `JakartaEE10` recipe. The migration includes namespace changes (e.g., `javax` to `jakarta`) and API adjustments, such as removing trailing `/*` from `@ApplicationPath`. ```xml org.openrewrite.maven rewrite-maven-plugin 5.43.0 org.openrewrite.java.migrate.jakarta.JakartaEE10 org.openrewrite.recipe rewrite-migrate-java 2.28.0 ``` ```java // Before: javax namespace (Java EE 8) import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.ApplicationPath; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.enterprise.context.RequestScoped; @ApplicationPath("/api/*") public class MyApplication extends Application {} @Path("/hello") @RequestScoped public class HelloResource { @GET public String hello() { return "Hello World"; } } // After: jakarta namespace (Jakarta EE 10) import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.ws.rs.ApplicationPath; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; import jakarta.enterprise.context.RequestScoped; @ApplicationPath("/api") // Trailing /* removed (Jakarta EE 10 requirement) public class MyApplication extends Application {} @Path("/hello") @RequestScoped public class HelloResource { @GET public String hello() { return "Hello World"; } } ``` -------------------------------- ### Develop Custom OpenRewrite Java Migration Recipe Source: https://context7.com/openrewrite/rewrite-migrate-java/llms.txt This Java code demonstrates how to create a custom OpenRewrite migration recipe. It uses a Java visitor pattern to find and transform specific method invocations, such as replacing a legacy logger with SLF4J. ```java // Custom recipe example package com.example; import org.openrewrite.*; import org.openrewrite.java.*; import org.openrewrite.java.tree.*; public class MigrateLegacyLogger extends Recipe { @Override public String getDisplayName() { return "Migrate legacy Logger to SLF4J"; } @Override public String getDescription() { return "Replaces com.example.LegacyLogger with org.slf4j.Logger"; } @Override public TreeVisitor getVisitor() { return new JavaIsoVisitor() { @Override public J.MethodInvocation visitMethodInvocation( J.MethodInvocation method, ExecutionContext ctx) { J.MethodInvocation mi = super.visitMethodInvocation(method, ctx); if (mi.getSimpleName().equals("log") && mi.getSelect() != null && TypeUtils.isOfClassType(mi.getSelect().getType(), "com.example.LegacyLogger")) { // Transform to SLF4J maybeAddImport("org.slf4j.Logger"); maybeRemoveImport("com.example.LegacyLogger"); return mi.withName(mi.getName().withSimpleName("info")); } return mi; } }; } } ``` -------------------------------- ### Upgrade Java Version Across Build Files Source: https://context7.com/openrewrite/rewrite-migrate-java/llms.txt This recipe programmatically updates build files (Maven `pom.xml` and Gradle `build.gradle`) and markers to target a specific Java version, such as Java 17. It simplifies the process of migrating projects to newer Java versions by ensuring consistency in source and target compatibility settings. ```java // Custom recipe using UpgradeJavaVersion package com.example; import org.openrewrite.*; import org.openrewrite.java.migrate.UpgradeJavaVersion; import java.util.Arrays; import java.util.List; public class StandardizeOnJava17 extends Recipe { @Override public String getDisplayName() { return "Standardize on Java 17"; } @Override public List getRecipeList() { return Arrays.asList( new UpgradeJavaVersion(17), new MyCustomPostMigrationChecks() ); } } ``` ```groovy // Before: build.gradle plugins { id 'java' } sourceCompatibility = '8' targetCompatibility = '8' // After: build.gradle (Java 17) plugins { id 'java' } java { toolchain { languageVersion = JavaLanguageVersion.of(17) } } ``` ```xml 8 8 17 ``` -------------------------------- ### Add-Opens Directives for Suppressing Illegal Reflective Access in JAR Manifests Source: https://github.com/openrewrite/rewrite-migrate-java/blob/main/README.md This XML snippet demonstrates how to add 'Add-Opens' directives to a JAR's manifest file to suppress illegal reflective access warnings and errors. These directives are applied to the top-level, executable JAR to ensure the Java runtime enforces the suppressions. Note that these directives cannot be applied to transitively included libraries. ```xml java.base/java.lang java.base/java.util java.base/java.lang.reflect java.base/java.text java.desktop/java.awt.font ``` -------------------------------- ### Modernize Generic Method Invocations with `var` Source: https://context7.com/openrewrite/rewrite-migrate-java/llms.txt This recipe replaces explicit generic types in variable declarations with the `var` keyword for method invocation results, improving code readability. It requires Java 10 or later and uses a visitor pattern for application. The transformation applies to declarations where the type can be inferred from the method call, such as `Collections.emptyMap()` or `Optional.of()`. ```java // Recipe class implementation package org.openrewrite.java.migrate.lang.var; import org.openrewrite.Recipe; import org.openrewrite.TreeVisitor; import org.openrewrite.ExecutionContext; import org.openrewrite.java.UsesJavaVersion; public class UseVarForGenericMethodInvocations extends Recipe { @Override public String getDisplayName() { return "Apply `var` to generic method invocations"; } @Override public TreeVisitor getVisitor() { return Preconditions.check( new UsesJavaVersion<>(10), new UseVarForGenericsVisitor() ); } } ``` ```java // Before: Explicit generic types Map> data = Collections.emptyMap(); List names = Arrays.asList("Alice", "Bob"); Optional result = Optional.of("value"); Stream numbers = Stream.of(1, 2, 3); Map> usersByDept = new HashMap<>(); List filtered = usersByDept .getOrDefault("Engineering", Collections.emptyList()) .stream() .map(User::getName) .collect(Collectors.toList()); // After: var with explicit type arguments when needed var data = Collections.>emptyMap(); var names = Arrays.asList("Alice", "Bob"); var result = Optional.of("value"); var numbers = Stream.of(1, 2, 3); var usersByDept = new HashMap>(); var filtered = usersByDept .getOrDefault("Engineering", Collections.emptyList()) .stream() .map(User::getName) .collect(Collectors.toList()); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.