Skip to main content

org.openrewrite.recipe

recipes-go​

License: Moderne Proprietary License

290 recipes

rewrite-all​

License: Apache License Version 2.0

3 recipes

  • org.openrewrite.FindCallGraph
    • Find call graph
    • Produces a data table where each row represents a method call.
  • org.openrewrite.FindDuplicateSourceFiles
    • Find duplicate source files
    • Record the presence of LSTs with duplicate paths, indicating that the same file was parsed more than once.
  • org.openrewrite.LanguageComposition
    • Language composition report
    • Counts the number of lines of the various kinds of source code and data formats parsed by OpenRewrite. Comments are not included in line counts. This recipe emits its results as two data tables, making no changes to any source file. One data table is per-file, the other is per-repository.

rewrite-android​

License: Moderne Proprietary License

28 recipes

rewrite-apache​

License: Moderne Source Available License

125 recipes

rewrite-circleci​

License: Moderne Proprietary License

2 recipes

rewrite-compiled-analysis​

License: Moderne Proprietary License

2 recipes

  • io.moderne.compiled.verification.ChangeListMethodAndVerify
    • Change List#add to List#plus and verify
    • We know this won't compile.
  • io.moderne.compiled.verification.VerifyCompilation
    • Verify compilation of changes made earlier in the same run
    • Recompile the source files that earlier recipes in this same recipe run changed, and mark the elements that no longer compile. This recipe examines only files carrying a RecipesThatMadeChanges marker, so running it on its own reports nothing at all, no matter how badly broken the code in the repository is. It is a verification step for a migration, not a standalone compiler. Compose it after the recipe whose output you want to verify: yaml type: specs.openrewrite.org/v1beta/recipe name: com.yourorg.MigrateAndVerify displayName: Migrate and verify description: Rename a method and verify that the result still compiles. recipeList: - org.openrewrite.java.ChangeMethodName: methodPattern: java.util.List add(..) newMethodName: plus - io.moderne.compiled.verification.VerifyCompilation Failures appear as inline warnings on the offending elements, so a run that produces no warnings either verified everything successfully or had nothing to verify.

rewrite-concourse​

License: Moderne Proprietary License

6 recipes

rewrite-cucumber-jvm​

License: Moderne Source Available License

26 recipes

  • org.openrewrite.cucumber.jvm.CollapseCucumberOptionsTags
    • Collapse @CucumberOptions tags into a single tag expression
    • Cucumber-JVM 6.0.0 narrowed @CucumberOptions#tags from String[] to a single String. The elements of the array were combined with and, such that tags = \{"@a", "@b"\} becomes tags = "(@a) and (@b)".
  • org.openrewrite.cucumber.jvm.CucumberAnnotationToSuite
    • Replace @Cucumber with @Suite
    • Replace @Cucumber with @Suite and @SelectClasspathResource("cucumber/annotated/class/package").
  • org.openrewrite.cucumber.jvm.CucumberApiToIoCucumber
    • Migrate cucumber.api to io.cucumber
    • Cucumber-JVM 5.0.0 moved the cucumber.api types to io.cucumber, but not as a single package rename: types were spread over io.cucumber.java, io.cucumber.junit, io.cucumber.testng, io.cucumber.plugin and io.cucumber.core. This recipe maps each cucumber.api type onto the package it actually moved to.
  • org.openrewrite.cucumber.jvm.CucumberJava8HookDefinitionToCucumberJava
    • Replace cucumber-java8 hook definition with cucumber-java
    • Replace LambdaGlue hook definitions with new annotated methods with the same body, or, for a method reference, with a body calling the method it refers to.
  • org.openrewrite.cucumber.jvm.CucumberJava8StepDefinitionToCucumberJava
    • Replace cucumber-java8 step definitions with cucumber-java
    • Replace StepDefinitionBody methods with StepDefinitionAnnotations on new methods with the same body, or, for a method reference, with a body calling the method it refers to.
  • org.openrewrite.cucumber.jvm.CucumberJava8ToJava
    • Migrate cucumber-java8 to cucumber-java
    • Migrates cucumber-java8 step definitions, LambdaGlue hooks and LambdaGlue type registrations to cucumber-java annotated methods.
  • org.openrewrite.cucumber.jvm.CucumberJava8TypeDefinitionToCucumberJava
    • Replace cucumber-java8 type definitions with cucumber-java
    • Replace LambdaGlue DataTableType, ParameterType, DocStringType and Default*Transformer registrations with cucumber-java annotated methods with the same body.
  • org.openrewrite.cucumber.jvm.CucumberOptionsPropertyToIndividualProperties
    • Migrate the cucumber.options property
    • Cucumber-JVM 6.0.0 removed cucumber.options, which passed command line options as a single string, in favour of an individual property per option. This recipe splits the property into its replacements, both in .properties files and in Maven Surefire or Failsafe systemPropertyVariables. Options without a property equivalent, such as --threads, have no migration path; there the property is left untouched, with a TODO comment added above it.
  • org.openrewrite.cucumber.jvm.CucumberOptionsToTestNgCucumberOptions
    • Migrate cucumber.api.CucumberOptions to io.cucumber.testng.CucumberOptions
    • Replace cucumber.api.CucumberOptions with the TestNG variant in source files that run through a TestNG runner.
  • org.openrewrite.cucumber.jvm.CucumberRunWithToSuite
    • Cucumber JUnit 4 @RunWith(Cucumber.class) to JUnit Platform @Suite
    • Replaces the Cucumber JUnit 4 runner with a JUnit Platform @Suite that runs the Cucumber engine. The @CucumberOptions become @ConfigurationParameter annotations, and the features become @SelectClasspathResource selectors where they are on the classpath. The JUnit 4 runner looks for glue in the package of the annotated class by default, and the Cucumber engine in the whole classpath, so that package becomes the explicit glue when none is configured. Class-level setup and teardown methods become @BeforeSuite and @AfterSuite methods, as a @Suite does not run @BeforeClass or @BeforeAll. A class that extends another class, which may contribute @CucumberOptions, or that has an option that cannot be carried over, such as one that refers to a constant, keeps the JUnit 4 runner, with a comment explaining why.
  • org.openrewrite.cucumber.jvm.CucumberToJunitPlatformSuite
    • Cucumber to JUnit test @Suite
    • Migrates Cucumber tests run by the @Cucumber annotation or the JUnit 4 @RunWith(Cucumber.class) runner to a JUnit Platform @Suite, and swaps cucumber-junit for cucumber-junit-platform-engine 7.x. Each Cucumber-JVM module depends on the cucumber-core of its own release, and the engine fails to run against any other, so the rest of the Cucumber-JVM dependencies move to that same 7.x.
  • org.openrewrite.cucumber.jvm.DropStrictAware
    • Drop StrictAware
    • Cucumber-JVM 8.0.0 removed StrictAware, which Cucumber-JVM 7 only ever called with setStrict(true). Remove it from implements along with the setStrict(boolean) override, and implement Plugin instead when the class implements no other plugin interface.
  • org.openrewrite.cucumber.jvm.DropStrictOption
    • Drop the strict option
    • Cucumber-JVM 7.0.0 removed the strict option, as scenarios are now always executed in strict mode.
  • org.openrewrite.cucumber.jvm.DropSummaryPrinter
    • Drop SummaryPrinter
    • Replace SummaryPrinter with Plugin, if not already present.
  • org.openrewrite.cucumber.jvm.DropTimeoutAttribute
    • Drop the timeout attribute
    • Cucumber-JVM 5.0.0 removed the timeout attribute from step definition and hook annotations, in favor of asserting on the duration from within the step definition itself.
  • org.openrewrite.cucumber.jvm.FixTeluguLanguageCode
    • Fix the Telugu language code
    • Cucumber-JVM 7.0.0 removed the incorrect ISO 639-1 code tl for Telugu, which is now consistently te.
  • org.openrewrite.cucumber.jvm.MigrateCucumberJava8ScenarioAndStatus
    • Migrate io.cucumber.java8.Scenario and io.cucumber.java8.Status
    • Scenario and Status are the only io.cucumber.java8 types with an io.cucumber.java counterpart; the language interfaces such as En and the LambdaGlue body types have none, so renaming the package wholesale would point whatever the migration could not convert at a type that does not exist. Where such a body type does survive it also still expects the cucumber-java8 Scenario, as in an anonymous HookBody, so leave both types be until the last of the lambda glue is gone.
  • org.openrewrite.cucumber.jvm.MigrateRuntimeOptionsBuilder
    • Migrate RuntimeOptionsBuilder
    • Cucumber-JVM 7.0.0 dropped RuntimeOptionsBuilder.addDefaultFormatterIfAbsent(), as no formatter is added implicitly any more, and renamed addDefaultSummaryPrinterIfAbsent() to addDefaultSummaryPrinterIfNotDisabled(), which defers to the new setNoSummary(). Mirrors the change Cucumber-JVM made to its own io.cucumber.core.cli.Main, which projects that run Cucumber programmatically tend to have copied.
  • org.openrewrite.cucumber.jvm.MigrateScenarioWriteAndEmbed
    • Migrate Scenario.write and Scenario.embed
    • Cucumber-JVM 6.0.0 removed Scenario.write(String) and Scenario.embed(byte[], String) along with Scenario.embed(byte[], String, String), in favor of Scenario.log(String) and Scenario.attach(byte[], String, String). The two argument embed emitted an attachment without a name, which attach expresses as a null name.
  • org.openrewrite.cucumber.jvm.RegexToCucumberExpression
    • Replace cucumber-java step definition regexes with Cucumber expressions
    • Strip regex prefix and suffix from step annotation expressions arguments where possible.
  • org.openrewrite.cucumber.jvm.RemoveCucumberJava8Dependency
    • Remove cucumber-java8 once nothing is left needing it
    • Removes the cucumber-java8 dependency where every LambdaGlue call migrates to cucumber-java, and retains it wherever one is left behind. Read from the glue as it stands before the migration, as what the migration leaves behind only becomes visible to a scanning recipe in the cycle after, which a build tool run never reaches. Glue left anywhere retains the dependency everywhere, an unused dependency being the one outcome here that still compiles.
  • org.openrewrite.cucumber.jvm.TypeRegistryConfigurerToAnnotations
    • Replace TypeRegistryConfigurer with cucumber-java annotations
    • Cucumber-JVM 7.0.0 removed TypeRegistryConfigurer; replace implementations with @ParameterType, @DataTableType, @DocStringType and @Default*Transformer annotated glue methods. Classes whose configureTypeRegistry method cannot be converted in full are left untouched, with a TODO comment added above the registration that could not be converted.
  • org.openrewrite.cucumber.jvm.UpgradeCucumber2x
    • Upgrade to Cucumber-JVM 2.x
    • Upgrade to Cucumber-JVM 2.x from any previous version.
  • org.openrewrite.cucumber.jvm.UpgradeCucumber5x
    • Upgrade to Cucumber-JVM 5.x
    • Upgrade to Cucumber-JVM 5.x from any previous version.
  • org.openrewrite.cucumber.jvm.UpgradeCucumber6x
    • Upgrade to Cucumber-JVM 6.x
    • Upgrade to Cucumber-JVM 6.x from any previous version.
  • org.openrewrite.cucumber.jvm.UpgradeCucumber7x
    • Upgrade to Cucumber-JVM 7.x
    • Upgrade to Cucumber-JVM 7.x from any previous version.

rewrite-dotnet​

License: Moderne Proprietary License

7 recipes

rewrite-feature-flags​

License: Moderne Source Available License

33 recipes

rewrite-github-actions​

License: Moderne Source Available License

63 recipes

rewrite-gitlab​

License: Moderne Source Available License

22 recipes

rewrite-hibernate​

License: Moderne Source Available License

30 recipes

rewrite-jackson​

License: Apache License Version 2.0

49 recipes

  • org.openrewrite.java.jackson.AddJsonCreatorToPrivateConstructors
    • Add @JsonCreator to non-public constructors
    • Jackson 3 strictly enforces creator visibility rules. Non-public constructors in Jackson-annotated classes that were auto-detected in Jackson 2 need an explicit @JsonCreator annotation to work for deserialization in Jackson 3.
  • org.openrewrite.java.jackson.AddMissingJacksonDependencies
    • Add missing Jackson dataformat dependencies
    • Adds Jackson dataformat dependencies when code uses types from their packages but the dependency is not declared. For example, adds jackson-dataformat-xml when code uses XmlMapper.
  • org.openrewrite.java.jackson.CodehausClassesToFasterXML
    • Migrate classes from Jackson Codehaus (legacy) to Jackson FasterXML
    • In Jackson 2, the package and dependency coordinates moved from Codehaus to FasterXML.
  • org.openrewrite.java.jackson.CodehausToFasterXML
    • Migrate from Jackson Codehaus (legacy) to Jackson FasterXML
    • In Jackson 2, the package and dependency coordinates moved from Codehaus to FasterXML.
  • org.openrewrite.java.jackson.CommentOutSimpleModuleMethodCalls
    • Add comment to SimpleModule method calls on modules that no longer extend SimpleModule
    • In Jackson 3, some modules (e.g. JodaModule) no longer extend SimpleModule and instead extend JacksonModule directly. This means methods like addSerializer() and addDeserializer() are no longer available on these types. This recipe adds a TODO comment to flag these call sites for manual migration.
  • org.openrewrite.java.jackson.FindJsonSetterNullsAsEmptyCollections
    • Find @JsonSetter(nulls = Nulls.AS_EMPTY) on empty collection fields
    • Find Map and Collection fields that carry @JsonSetter(nulls = Nulls.AS_EMPTY), are initialized with an empty collection, and are no longer hidden by @JsonIgnore on the field or its getter, or by a class level @JsonIgnoreProperties. In rewrite-jackson 1.17.0 through 1.28.0 the Jackson 2 to 3 migration replaced @JsonIgnore with @JsonSetter(nulls = Nulls.AS_EMPTY) on exactly these fields, which starts serializing properties that were deliberately hidden wherever the field is otherwise visible, such as through a getter. Run this recipe to audit repositories migrated with those versions; every match that should stay out of the JSON output needs @JsonIgnore restored, which the addJsonIgnore option does for you.
  • org.openrewrite.java.jackson.IOExceptionToJacksonException
    • Replace IOException with JacksonException in catch clauses
    • In Jackson 3, ObjectMapper and related classes no longer throw IOException. This recipe replaces catch (IOException e) with catch (JacksonException e) when the try block contains Jackson API calls. When the try block also contains non-Jackson code that throws IOException, the catch is changed to a multi-catch catch (JacksonException | IOException e).
  • org.openrewrite.java.jackson.Jackson3JsonNodeFieldIterators
    • Migrate JSONNode field iterator for Jackson 3
    • JSONNode fields are using Collections instead of Iterator singe Jackson 3. To mimic Jackson 2s behavior an additional call to Collection#iterator()is needed.
  • org.openrewrite.java.jackson.JacksonBestPractices
    • Jackson best practices
    • Apply best practices for using Jackson library, including upgrade to Jackson 2.x and removing redundant annotations.
  • org.openrewrite.java.jackson.JsonSerializeIncludeToJsonInclude
    • Migrate deprecated @JsonSerialize(include = ...) to @JsonInclude
    • Move the deprecated include attribute of FasterXML's @JsonSerialize to a separate @JsonInclude annotation. The include attribute was deprecated in Jackson 2.x and removed in Jackson 3.x; running this recipe before the Jackson 2 → 3 package rename produces a correct tools.jackson.annotation.JsonInclude on the Jackson 3 side.
  • org.openrewrite.java.jackson.LombokJacksonizedConfig
    • Update lombok.config for Jackson 3 compatibility
    • When @Jacksonized is used, Lombok generates Jackson annotations. By default it generates Jackson 2.x annotations. This recipe adds lombok.jacksonized.jacksonVersion += 3 to lombok.config so Lombok generates Jackson 3 compatible annotations.
  • org.openrewrite.java.jackson.MigrateFactorySettersToBuilder
    • Migrate factory setter calls to builder pattern
    • In Jackson 3, JsonFactory is immutable and new JsonFactory() is no longer the right entry point: the concrete factory lives at tools.jackson.core.json.JsonFactory and is constructed via JsonFactory.builder()...build(). Configuration methods like enable, disable, configure, setCharacterEscapes, etc. must be called on the builder instead. This recipe migrates setter calls to the builder pattern when safe, or adds TODO comments when automatic migration is not possible.
  • org.openrewrite.java.jackson.MigrateMapperSettersToBuilder
    • Migrate mapper setter calls to builder pattern
    • In Jackson 3, JsonMapper and other format-aligned mappers are immutable. Configuration methods like setFilterProvider, addMixIn, disable, enable, etc. must be called on the builder instead. This recipe migrates setter calls to the builder pattern when safe, or adds TODO comments when automatic migration is not possible.
  • org.openrewrite.java.jackson.ModuleStillOnJackson2
    • Find modules still on Jackson 2
    • Marks the source files of modules that either do not resolve Jackson 3 yet, or still use Jackson 2 types in their own sources or those of their child modules. Modules that already resolve Jackson 3 and no longer use Jackson 2 types are left unmarked, as any Jackson 2 dependencies they still declare are there on purpose, for instance for generated sources that are not part of the LST.
  • org.openrewrite.java.jackson.ReadValueUrlToOpenStream
    • Migrate ObjectMapper.readValue(URL, ...) to use openStream()
    • Jackson 3.x removed every URL-accepting readValue overload from ObjectMapper. Rewrite call sites to feed URL.openStream() into the surviving readValue(InputStream, ...) overload, which is what readValue(URL, ...) did internally in Jackson 2.x. The caller's checked-exception story is unchanged: URL.openStream() declares IOException, the same checked exception the removed readValue(URL, ...) declared.
  • org.openrewrite.java.jackson.RemoveBuiltInModuleBeans
    • Remove Spring beans for modules built-in to Jackson 3
    • Jackson 3 includes Java time, JDK 8 and parameter name support in databind and removes their module classes. Remove Spring @Bean methods that only return a new default instance of one of these modules. Customized, overridden or directly referenced factories are left for manual migration.
  • org.openrewrite.java.jackson.RemoveBuiltInModuleRegistrations
    • Remove registrations of modules built-in to Jackson 3
    • In Jackson 3, ParameterNamesModule, Jdk8Module, and JavaTimeModule are built into jackson-databind and no longer need to be registered manually. This recipe removes ObjectMapper.registerModule() and MapperBuilder.addModule() calls for these modules.
  • org.openrewrite.java.jackson.RemoveDeadJacksonThrows
    • Remove dead throws declarations for unchecked Jackson exceptions
    • In Jackson 3 the exception hierarchy is rerooted under JacksonException, which extends RuntimeException. Any surviving throws for a Jackson exception type is dead: callers are not required to handle it, and the declaration misleads readers into thinking checked-exception handling is needed. Removes throws for JacksonException and its subtypes (e.g. DatabindException) from both methods and constructors. Assumes the Jackson 2 to 3 package changes have already run, so all Jackson exception types live under tools.jackson. Does not touch throws IOException (still a checked exception) or non-Jackson exception types.
  • org.openrewrite.java.jackson.RemoveRedundantFeatureFlags
    • Remove redundant Jackson 3 feature flag configurations
    • Remove ObjectMapper feature flag configurations that set values to their new Jackson 3 defaults. For example, disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) and configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) are redundant since this is now disabled by default in Jackson 3.
  • org.openrewrite.java.jackson.RemoveRedundantJsonPropertyValue
    • Remove redundant @JsonProperty argument
    • Remove @JsonProperty annotation or value attribute when the value matches the argument name.
  • org.openrewrite.java.jackson.ReplaceIOExceptionThrowInJacksonOverrides
    • Replace throw new IOException(..) inside Jackson serializer / deserializer overrides
    • In Jackson 3, serialize() and deserialize() methods no longer declare throws IOException. This recipe removes the throws IOException declaration from overrides of JsonSerializer.serialize, JsonSerializer.serializeWithType, JsonDeserializer.deserialize, and JsonDeserializer.deserializeWithType, and rewrites throw new IOException(msg[, cause]) inside those overrides to JsonMappingException.from(<generator|parser>, msg[, cause]). A companion type change later migrates JsonMappingException to tools.jackson.databind.DatabindException.
  • org.openrewrite.java.jackson.ReplaceObjectMapperCopy
    • Replace ObjectMapper.copy() with rebuild().build()
    • In Jackson 3, ObjectMapper.copy() was removed. Use mapper.rebuild().build() instead.
  • org.openrewrite.java.jackson.ReplacePropertyNamingStrategyConstants
    • Replace deprecated PropertyNamingStrategy inner classes and constants
    • Replace usages of deprecated PropertyNamingStrategy inner classes and constants with their PropertyNamingStrategies equivalents, introduced in Jackson 2.12.
  • org.openrewrite.java.jackson.ReplaceStreamWriteCapability
    • Replace removed JsonGenerator capability methods with StreamWriteCapability
    • In Jackson 3, JsonGenerator.canWriteBinaryNatively() and canWriteFormattedNumbers() were removed and replaced with the StreamWriteCapability enum. This recipe updates these method calls to use getWriteCapabilities().isEnabled(StreamWriteCapability.*) instead.
  • org.openrewrite.java.jackson.SimplifyJacksonExceptionCatch
    • Simplify catch clauses for Jackson exceptions
    • In Jackson 3, JacksonException and its subtypes extend RuntimeException. This recipe simplifies multi-catch clauses by removing Jackson exception types when RuntimeException is also caught, since catching both is redundant. For example, catch (JacksonException | RuntimeException e) becomes catch (RuntimeException e).
  • org.openrewrite.java.jackson.StdDeserializerNullConstructor
    • Replace null type in StdDeserializer constructor with actual type
    • In Jackson 3, StdDeserializer no longer accepts null for the handled type parameter. This recipe replaces this(null) and super((Class<?>) null) in StdDeserializer subclass constructors with the actual type parameter from the class declaration.
  • org.openrewrite.java.jackson.UpdateAutoDetectVisibilityConfiguration
    • Replace disable(MapperFeature.AUTO_DETECT_*) with changeDefaultVisibility() for Jackson 3
    • In Jackson 3, auto-detection MapperFeature flags like AUTO_DETECT_FIELDS are removed. Use changeDefaultVisibility() on the builder instead.
  • org.openrewrite.java.jackson.UpdateSerializationInclusionConfiguration
    • Update configuration of serialization inclusion in ObjectMapper for Jackson 3
    • In Jackson 3, mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL) is no longer supported and should be replaced by changeDefaultPropertyInclusion() for both valueInclusion and contentInclusion.
  • org.openrewrite.java.jackson.UpgradeJackson_2_3
    • Migrates from Jackson 2.x to Jackson 3.x
    • Migrate applications to the latest Jackson 3.x release. This recipe handles package changes (com.fasterxml.jackson -> tools.jackson), dependency updates, core class renames, exception renames, and method renames (e.g., JsonGenerator.writeObject() -> writePOJO(), JsonParser.getCurrentValue() -> currentValue()).
  • org.openrewrite.java.jackson.UpgradeJackson_2_3_Dependencies
    • Upgrade Jackson 2.x dependencies to 3.x
    • Upgrade Jackson Maven dependencies from 2.x to 3.x versions and update group IDs. Modules that already resolve Jackson 3 and no longer use Jackson 2 types in their sources are left as-is, as any Jackson 2 dependencies they still declare are there on purpose.
  • org.openrewrite.java.jackson.UpgradeJackson_2_3_JsonGeneratorMethodRenames
    • Rename Jackson 2.x methods to 3.x equivalents for JsonGenerator
    • Rename JsonGenerator methods that were renamed in 3.x (e.g., writeObject() to writePOJO(), getCurrentValue() to currentValue()).
  • org.openrewrite.java.jackson.UpgradeJackson_2_3_JsonNodeMethodRenames
    • Rename Jackson 2.x methods to 3.x equivalents for JsonNode
    • Rename JsonNode methods that were renamed in 3.x (e.g., elements() to values(), fields() to entries()).
  • org.openrewrite.java.jackson.UpgradeJackson_2_3_JsonParserMethodRenames
    • Rename Jackson 2.x methods to 3.x equivalents for JsonParser
    • Rename JsonParser methods that were renamed in 3.x (e.g., getTextCharacters() to getStringCharacters(), getCurrentValue() to currentValue()).
  • org.openrewrite.java.jackson.UpgradeJackson_2_3_MethodRenames
    • Rename Jackson 2.x methods to 3.x equivalents
    • Rename Jackson methods that were renamed in 3.x (e.g., writeObject() to writePOJO(), getCurrentValue() to currentValue()).
  • org.openrewrite.java.jackson.UpgradeJackson_2_3_ModernizeJacksonCoreFeatures
    • Modernize legacy jackson-core feature constants
    • Jackson 2.10 moved most flag constants out of JsonParser.Feature and JsonGenerator.Feature into the new JsonReadFeature / JsonWriteFeature (for JSON-specific flags) and StreamReadFeature / StreamWriteFeature (for format-agnostic flags). Jackson 3 keeps only the modern locations. This recipe rewrites every legacy constant to its Jackson 2-modern equivalent so the rest of the Jackson 2 → 3 pipeline (in particular the builder migrations) sees flags the modern API will accept.
  • org.openrewrite.java.jackson.UpgradeJackson_2_3_ObjectNodeMethodRenames
    • Rename Jackson 2.x methods to 3.x equivalents for ObjectNode
    • Rename ObjectNode methods deprecated in Jackson 2 and removed in 3.x (put(String, JsonNode) to set, putAll to setAll).
  • org.openrewrite.java.jackson.UpgradeJackson_2_3_PackageChanges
    • Update Jackson package names from 2.x to 3.x
    • Update Jackson package imports from com.fasterxml.jackson to tools.jackson.
  • org.openrewrite.java.jackson.UpgradeJackson_2_3_RelocatedFeatureConstants
    • Migrate relocated feature constants to DateTimeFeature and EnumFeature
    • Jackson 3 moved date/time-related feature constants from SerializationFeature and DeserializationFeature into DateTimeFeature, and enum-related constants into EnumFeature.
  • org.openrewrite.java.jackson.UpgradeJackson_2_3_RemoveRedundantFeatureFlags
    • Remove redundant Jackson 3 feature flag configurations
    • Remove ObjectMapper feature flag configurations that are now defaults in Jackson 3.
  • org.openrewrite.java.jackson.UpgradeJackson_2_3_TypeChanges
    • Update Jackson 2.x types to 3.x
    • Update Jackson type names including exception types and core class renames.
  • org.openrewrite.java.jackson.UseFormatAlignedObjectMappers
    • Use format alignment ObjectMappers
    • Replace wrapping ObjectMapper calls with their format aligned implementation.
  • org.openrewrite.java.jackson.UseJsonFactoryStaticBuilder
    • Use JsonFactory.builder() over new JsonFactoryBuilder()
    • After the Jackson 2 → 3 migration, prefer the concrete static JsonFactory.builder() entry over new JsonFactoryBuilder() so JsonFactory chains read the same way as the format-aligned factories (YAMLFactory.builder(), CBORFactory.builder(), etc.). The reason MigrateFactorySettersToBuilder emits new JsonFactoryBuilder() in the first place is a Jackson 2 quirk — JsonFactory.builder() returned the wildcard TSFBuilder<?, ?> there. In Jackson 3 the static returns a concretely-typed JsonFactoryBuilder, so the constructor form no longer earns its keep.
  • org.openrewrite.java.jackson.UseModernDateTimeSerialization
    • Use modern date/time serialization defaults
    • Remove redundant @JsonFormat annotations on java.time types that specify ISO-8601 patterns, as Jackson 3 uses ISO-8601 as the default format (with WRITE_DATES_AS_TIMESTAMPS now disabled by default).
  • org.openrewrite.java.jackson.UseReadTreeAsValueInDeserializer
    • Use DeserializationContext.readTreeAsValue() instead of ObjectCodec.treeToValue()
    • In Jackson 3, ObjectCodec is replaced by ObjectReadContext, which does not expose treeToValue. The equivalent method is readTreeAsValue(JsonNode, Class) on DeserializationContext. This recipe rewrites parser.getCodec().treeToValue(node, Foo.class) to ctxt.readTreeAsValue(node, Foo.class) inside methods that have a DeserializationContext parameter (typically JsonDeserializer.deserialize).
  • org.openrewrite.java.jackson.codehaus.CodehausDependencyToFasterXML
    • Migrate dependencies from Jackson Codehaus (legacy) to FasterXML
    • Replace Codehaus Jackson dependencies with FasterXML Jackson dependencies, and add databind if needed.
  • org.openrewrite.java.jackson.codehaus.JsonIncludeAnnotation
    • Migrate to Jackson @JsonInclude
    • Move Codehaus' @JsonSerialize.include argument to FasterXMLs @JsonInclude annotation.
  • org.openrewrite.java.jackson.codehaus.RemoveDoublyAnnotatedCodehausAnnotations
    • Remove Codehaus Jackson annotations if doubly annotated
    • Remove Codehaus Jackson annotations if they are doubly annotated with Jackson annotations from the com.fasterxml.jackson package.
  • org.openrewrite.java.jackson.codehaus.ReplaceSerializationConfigAnnotationIntrospector
    • Migrate serialization annotation processor
    • Migrate serialization annotation processor to use the codehaus config method.
  • org.openrewrite.java.jackson.codehaus.TransferJsonSerializeArgumentsFromCodehausToFasterXML
    • Transfer @JsonSerialize arguments from Codehaus to FasterXML
    • Transfer @JsonSerialize annotation arguments (using, contentUsing, keyUsing, nullUsing) from Codehaus to FasterXML. If the argument was set already, it will not be transferred.

rewrite-java-dependencies​

License: Apache License Version 2.0

18 recipes

  • org.openrewrite.java.dependencies.AddDependency
    • Add Gradle or Maven dependency
    • For a Gradle project, add a gradle dependency to a build.gradle file in the correct configuration based on where it is used. Or For a maven project, Add a Maven dependency to a pom.xml file in the correct scope based on where it is used.
  • org.openrewrite.java.dependencies.ChangeDependency
    • Change Gradle or Maven dependency
    • Change the group ID, artifact ID, and/or the version of a specified Gradle or Maven dependency.
  • org.openrewrite.java.dependencies.DependencyInsight
    • Dependency insight for Gradle and Maven
    • Finds dependencies, including transitive dependencies, in both Gradle and Maven projects. Matches within all Gradle dependency configurations and Maven scopes.
  • org.openrewrite.java.dependencies.DependencyList
    • Dependency report
    • Emits a data table detailing all Gradle and Maven dependencies. This recipe makes no changes to any source file.
  • org.openrewrite.java.dependencies.DependencyResolutionDiagnostic
    • Dependency resolution diagnostic
    • Recipes which manipulate dependencies must be able to successfully access the artifact repositories and resolve dependencies from them. This recipe produces two data tables used to understand the state of dependency resolution. The Repository accessibility report lists all the artifact repositories known to the project and whether respond to network access. The network access is attempted while the recipe is run and so is representative of current conditions. The Gradle dependency configuration errors lists all the dependency configurations that failed to resolve one or more dependencies when the project was parsed. This is representative of conditions at the time the LST was parsed.
  • org.openrewrite.java.dependencies.FindDependency
    • Find Maven and Gradle dependencies
    • Finds direct dependencies declared in Maven and Gradle build files. This does not search transitive dependencies. To detect both direct and transitive dependencies use org.openrewrite.java.dependencies.DependencyInsight This recipe works for both Maven and Gradle projects.
  • org.openrewrite.java.dependencies.FindRepositoryOrder
    • Maven repository order
    • Determine the order in which dependencies will be resolved for each pom.xml or build.gradle based on its defined repositories and effective settings.
  • org.openrewrite.java.dependencies.RelocatedDependencyCheck
    • Find relocated dependencies
    • Find Maven and Gradle dependencies and Maven plugins that have relocated to a new groupId or artifactId. Relocation information comes from the oga-maven-plugin maintained by Jonathan Lermitage, Filipe Roque and others. This recipe makes no changes to any source file by default. Add changeDependencies=true to change dependencies, but note that you might need to run additional recipes to update imports and adopt other breaking changes.
  • org.openrewrite.java.dependencies.RemoveDependency
    • Remove a Gradle or Maven dependency
    • For Gradle project, removes a single dependency from the dependencies section of the build.gradle. For Maven project, removes a single dependency from the <dependencies> section of the pom.xml.
  • org.openrewrite.java.dependencies.RemoveRedundantDependencies
    • Remove redundant explicit dependencies
    • Remove explicit dependencies that are already provided transitively by a specified dependency. This recipe downloads and resolves the parent dependency's POM to determine its true transitive dependencies, allowing it to detect redundancies even when both dependencies are explicitly declared. A direct dependency is only removed when the transitive one provides it at the exact same scope and with the same declared exclusions, so that removing it does not change the effective classpath. Declarations that constrain resolution through a version range or dynamic version, such as a Gradle version \{ strictly ... \} block, are never removed.
  • org.openrewrite.java.dependencies.UpgradeDependencyVersion
    • Upgrade Gradle or Maven dependency versions
    • For Gradle projects, upgrade the version of a dependency in a build.gradle file. Supports updating dependency declarations of various forms: * String notation: "group:artifact:version" * Map notation: group: 'group', name: 'artifact', version: 'version' It is possible to update version numbers which are defined earlier in the same file in variable declarations. For Maven projects, upgrade the version of a dependency by specifying a group ID and (optionally) an artifact ID using Node Semver advanced range selectors, allowing more precise control over version updates to patch or minor releases.
  • org.openrewrite.java.dependencies.UpgradeTransitiveDependencyVersion
    • Upgrade transitive Gradle or Maven dependencies
    • Upgrades the version of a transitive dependency in a Maven pom.xml or Gradle build.gradle. Leaves direct dependencies unmodified. Can be paired with the regular Upgrade Dependency Version recipe to upgrade a dependency everywhere, regardless of whether it is direct or transitive.
  • org.openrewrite.java.dependencies.search.DoesNotIncludeDependency
    • Does not include dependency for Gradle and Maven
    • A precondition which returns false if visiting a Gradle file / Maven pom which includes the specified dependency in the classpath of some Gradle configuration / Maven scope. For compatibility with multimodule projects, this should most often be applied as a precondition.
  • org.openrewrite.java.dependencies.search.FindDuplicateClasses
    • Find duplicate classes on the classpath
    • Detects classes that appear in multiple dependencies on the classpath. This is similar to what the Maven duplicate-finder-maven-plugin does. Duplicate classes can cause runtime issues when different versions of the same class are loaded.
  • org.openrewrite.java.dependencies.search.FindMinimumDependencyVersion
    • Find the oldest matching dependency version in use
    • The oldest dependency version in use is the lowest dependency version in use in any source set of any subproject of a repository. It is possible that, for example, the main source set of a project uses Jackson 2.11, but a test source set uses Jackson 2.16. In this case, the oldest Jackson version in use is Java 2.11.
  • org.openrewrite.java.dependencies.search.FindMinimumJUnitVersion
    • Find minimum JUnit version
    • A recipe to find the minimum version of JUnit dependencies. This recipe is designed to return the minimum version of JUnit in a project. It will search for JUnit 4 and JUnit 5 dependencies in the project. If both versions are found, it will return the minimum version of JUnit 4. If a minimumVersion is provided, the recipe will search to see if the minimum version of JUnit used by the project is no lower than the minimumVersion. For example: if the minimumVersion is 4, and the project has JUnit 4.12 and JUnit 5.7, the recipe will return JUnit 4.12. If the project has only JUnit 5.7, the recipe will return JUnit 5.7. Another example: if the minimumVersion is 5, and the project has JUnit 4.12 and JUnit 5.7, the recipe will not return any results.
  • org.openrewrite.java.dependencies.search.ModuleHasDependency
    • Module has dependency
    • Searches for both Gradle and Maven modules that have a dependency matching the specified groupId and artifactId. Places a SearchResult marker on all sources within a module with a matching dependency. This recipe is intended to be used as a precondition for other recipes. For example this could be used to limit the application of a spring boot migration to only projects that use spring-boot-starter, limiting unnecessary upgrading. If the search result you want is instead just the build.gradle(.kts) or pom.xml file applying the plugin, use the FindDependency recipe instead.
  • org.openrewrite.java.dependencies.search.RepositoryHasDependency
    • Repository has dependency
    • Searches for both Gradle and Maven modules that have a dependency matching the specified groupId and artifactId. Places a SearchResult marker on all sources within a repository with a matching dependency. This recipe is intended to be used as a precondition for other recipes. For example this could be used to limit the application of a spring boot migration to only projects that use a springframework dependency, limiting unnecessary upgrading. If the search result you want is instead just the build.gradle(.kts) or pom.xml file applying the plugin, use the FindDependency recipe instead.

rewrite-java-security​

License: Moderne Proprietary License

157 recipes

  • org.openrewrite.ai.security.FindMissingStructuredOutput
    • Find LLM freeform output flowing into a structured parser (OWASP LLM01)
    • Find code where the plain-text output of an LLM chat call flows into a structured parser (ObjectMapper.readValue/readTree, Gson.fromJson). Model output is read through the LangChain4j, Spring AI, OpenAI, Anthropic, and Azure AI Inference Java SDKs. The caller expects JSON but nothing enforced structured output on the model call — an attacker who influences the prompt (any LLM01 vector) can break parsing or steer downstream logic by producing content the parser accepts as valid but that carries injected instructions. Fix by switching to a schema-enforcing call: LangChain4j structured output APIs, Spring AI .entity(...), or provider-native JSON mode / tool use. Taint tracking follows the value through user-defined transformations between the model call and the parser.
  • org.openrewrite.ai.security.FindPromptInjection
    • Find prompt injection (OWASP LLM01)
    • Find HTTP request data that flows into an LLM prompt without intermediate validation. Sources are servlet request accessors (getParameter, getHeader, getReader, getInputStream), Spring WebRequest accessors, and Spring MVC handler parameters bound with @RequestParam, @PathVariable, @RequestHeader, @RequestBody, @RequestPart, @CookieValue, or @MatrixVariable; sinks are the message-content methods of the OpenAI, Anthropic, Azure AI Inference, LangChain4j, and Spring AI Java SDKs. A hit means the untrusted string reaches the model text without leaving the method and warrants a guardrail (allowlist, structured input, or provider-side guardrail).
  • org.openrewrite.ai.security.FindUnguardedRagInput
    • Find unguarded RAG content flowing into an LLM prompt (OWASP LLM01)
    • Find external content (HTTP responses, file reads, RestTemplate calls) that flows into an LLM prompt. This is the indirect-injection shape of OWASP LLM01: an attacker who can plant text in a fetched document or endpoint response steers the model through content the developer implicitly trusts. Taint tracking follows the value through user-defined transformations, none of which are assumed to sanitize, so review each hit for an existing guardrail (sanitizer, structured input, or provider-side guardrail).
  • org.openrewrite.ai.security.FindUnrestrictedPromptSelection
    • Find unrestricted prompt selection (OWASP LLM01)
    • Find code where untrusted input picks which LLM prompt template runs. Concretely, an HTTP request value — a servlet or Spring WebRequest accessor, or a Spring MVC handler parameter bound with @RequestParam, @PathVariable, @RequestHeader, @RequestBody, @RequestPart, @CookieValue, or @MatrixVariable — flows into a Map.get(...) key argument, and the value returned by that map lookup flows into an LLM prompt sink. This is the OWASP LLM01 shape where an attacker can jailbreak or escalate by switching to a system prompt they shouldn't be able to reach (tenant-prompt escape, admin templates, etc.). Taint tracking follows both legs of the flow through user-defined transformations.
  • org.openrewrite.ai.security.OwaspLlm01
    • OWASP LLM01 — Prompt Injection
    • OWASP LLM01 covers user or external input manipulating an LLM's behavior — overriding system prompts, exfiltrating data, or driving unsafe tool calls. This composite aggregates the individual detections that surface code shapes which let a prompt injection reach a model.
  • org.openrewrite.ai.security.OwaspLlmTop10
    • Remediate the OWASP Top 10 for LLM Applications
    • OWASP publishes a Top 10 for Large Language Model Applications describing the most impactful risks in LLM-integrated code. This umbrella recipe aggregates the per-category composites so customers can run the full sweep in one shot.
  • org.openrewrite.csharp.dependencies.DependencyInsight
    • Dependency insight for C#
    • Finds dependencies in *.csproj and packages.config.
  • org.openrewrite.csharp.dependencies.DependencyVulnerabilityCheck
    • Find and fix vulnerable Nuget dependencies
    • This software composition analysis (SCA) tool detects and upgrades dependencies with publicly disclosed vulnerabilities. Both direct and transitive dependencies are checked using the full dependency graph captured when the project's LST was built. Vulnerable direct dependencies are upgraded in place; vulnerable transitive dependencies are added as direct dependencies pinned to a fixed version. The target version is controlled with the versionSelection option. Before any change, the version constraints declared by every other package in the dependency graph are validated; when an upgrade would violate a constraint, an error marker describing the conflicting dependency path is added instead and no change is made. Vulnerability information comes from the GitHub Security Advisory Database, which aggregates vulnerability data from several public databases, including the National Vulnerability Database maintained by the United States government. Last updated: 2026-10-05T1104.
  • org.openrewrite.csharp.dependencies.FindEndOfLifeDependencies
    • Find end-of-life NuGet dependencies
    • Find NuGet packages whose upstream release is end-of-life or scheduled for end-of-life soon, using a snapshot of endoflife.date. Direct package references are marked in source; all matches (direct and transitive) are reported in the data table.
  • org.openrewrite.csharp.dependencies.SoftwareBillOfMaterials
    • Software bill of materials for C#
    • Produces a software bill of materials (SBOM) for each NuGet project. The SBOM lists every package reference, including transitive packages when the project was restored, in the CycloneDX XML format, in a file named sbom.xml adjacent to the *.csproj or packages.config.
  • org.openrewrite.csharp.dependencies.UpgradeDependencyVersion
    • Upgrade C# dependency versions
    • Upgrades dependencies in *.csproj, Directory.Packages.props, and packages.config. Only declarations at a lower exact or pinned version are changed.
  • org.openrewrite.dependencies.endoflife.FindEndOfLifeDependenciesDefault
    • Find end-of-life dependencies (defaults)
    • Flags Maven, Gradle, npm, and NuGet dependencies whose upstream release is end-of-life or reaches end-of-life within the next 180 days, using the bundled endoflife.date snapshot. Aggregates the per-ecosystem find-end-of-life recipes with their default settings.
  • org.openrewrite.golang.dependencies.DependencyVulnerabilityCheck
    • Find and fix vulnerable Go dependencies
    • This software composition analysis (SCA) tool detects and upgrades Go module dependencies with publicly disclosed vulnerabilities. This recipe both generates a report of vulnerable dependencies and upgrades go.mod to newer versions with fixes. This recipe by default only upgrades to the latest patch version. If a minor or major upgrade is required to reach the fixed version, this can be controlled using the maximumUpgradeDelta option. Vulnerability information comes from the GitHub Security Advisory Database, which aggregates vulnerability data from several public databases, including the National Vulnerability Database maintained by the United States government. When a go.sum file is present it is regenerated to match the upgraded go.mod by running go mod download, which requires the go toolchain to be installed. If the toolchain is unavailable the go.mod change is still applied and the go.sum is flagged so it can be brought back in sync with go mod tidy. Because the module graph is not re-resolved, upgrades that introduce new indirect requirements may still need a follow-up go mod tidy. ## Customizing Vulnerability Data This recipe can be customized by extending DependencyVulnerabilityCheckBase and overriding the vulnerability data sources: - baselineVulnerabilities(ExecutionContext ctx): Provides the default set of known vulnerabilities. The base implementation loads vulnerability data from the GitHub Security Advisory Database CSV file using ResourceUtils.parseResourceAsCsv(). Override this method to replace the entire vulnerability dataset with your own curated list. - supplementalVulnerabilities(ExecutionContext ctx): Allows adding custom vulnerability data beyond the baseline. The base implementation returns an empty list. Override this method to add organization-specific vulnerabilities, internal security advisories, or vulnerabilities from additional sources while retaining the baseline GitHub Advisory Database. Both methods return List<Vulnerability> objects. Vulnerability data can be loaded from CSV files using ResourceUtils.parseResourceAsCsv(path, Vulnerability.class, consumer) or constructed programmatically.
  • org.openrewrite.golang.dependencies.SoftwareBillOfMaterials
    • Software bill of materials for Go
    • Produces a software bill of materials (SBOM) for each Go module. The SBOM lists every module in the build list, at the version Go selects, in the CycloneDX XML format, in a file named sbom.xml adjacent to the go.mod.
  • org.openrewrite.golang.security.GoSecurityBestPractices
    • Go security best practices
    • Locates common security vulnerabilities in Go code, mirroring the checks performed by gosec.
  • org.openrewrite.golang.security.search.FindCommandInjection
    • Find command execution vectors in Go
    • Finds Go calls into os/exec (Command, CommandContext). When any part of the command or its arguments is derived from user input, these calls can allow OS command injection. Review each call site to ensure the executable and its arguments are not externally controlled.
  • org.openrewrite.golang.security.search.FindInsecureRandom
    • Find use of insecure random number generation in Go
    • Finds Go calls into math/rand and math/rand/v2. These generators are not cryptographically secure and must not be used to produce secrets, tokens, nonces, salts, or any other security-sensitive value. Use crypto/rand instead.
  • org.openrewrite.golang.security.search.FindInsecureTlsConfig
    • Find insecure TLS configuration in Go
    • Finds tls.Config literals that disable certificate verification by setting InsecureSkipVerify: true. This makes the connection vulnerable to man-in-the-middle attacks. Remove the field or set it to false and configure a proper certificate chain.
  • org.openrewrite.golang.security.search.FindSqlInjection
    • Find SQL injection vectors in Go
    • Finds query-executing methods on database/sql types (DB, Tx, Conn, Stmt). When a query string is built by concatenating user input rather than using bind parameters (? / $1 placeholders), these calls can allow SQL injection. Review each call site to ensure queries are parameterized.
  • org.openrewrite.golang.security.search.FindWeakCryptoAlgorithm
    • Find use of weak cryptographic algorithms in Go
    • Finds Go calls into crypto/md5, crypto/sha1, crypto/des, and crypto/rc4. These algorithms are cryptographically broken and should not be used for security-sensitive purposes such as hashing passwords, generating signatures, or encrypting data. Prefer SHA-256 or stronger (crypto/sha256, crypto/sha512) and AES (crypto/aes).
  • org.openrewrite.java.dependencies.AddExplicitTransitiveDependencies
    • Add explicit transitive dependencies
    • Detects when Java source code or configuration files reference types from transitive Maven dependencies and promotes those transitive dependencies to explicit direct dependencies in the pom.xml. This ensures the build is resilient against changes in transitive dependency trees of upstream libraries.
  • org.openrewrite.java.dependencies.DependencyLicenseCheck
    • Find licenses in use in third-party dependencies
    • Locates and reports on all licenses in use.
  • org.openrewrite.java.dependencies.DependencyVulnerabilityCheck
    • Find and fix vulnerable Maven/Gradle dependencies
    • This software composition analysis (SCA) tool detects and upgrades dependencies with publicly disclosed vulnerabilities. This recipe both generates a report of vulnerable dependencies and upgrades to newer versions with fixes. This recipe by default only upgrades to the latest patch version. If a minor or major upgrade is required to reach the fixed version, this can be controlled using the maximumUpgradeDelta option. Vulnerability information comes from the GitHub Security Advisory Database, which aggregates vulnerability data from several public databases, including the National Vulnerability Database maintained by the United States government. Upgrades dependencies versioned according to Semantic Versioning. ## Customizing Vulnerability Data This recipe can be customized by extending DependencyVulnerabilityCheckBase and overriding the vulnerability data sources: - baselineVulnerabilities(ExecutionContext ctx): Provides the default set of known vulnerabilities. The base implementation loads vulnerability data from the GitHub Security Advisory Database CSV file using ResourceUtils.parseResourceAsCsv(). Override this method to replace the entire vulnerability dataset with your own curated list. - supplementalVulnerabilities(ExecutionContext ctx): Allows adding custom vulnerability data beyond the baseline. The base implementation returns an empty list. Override this method to add organization-specific vulnerabilities, internal security advisories, or vulnerabilities from additional sources while retaining the baseline GitHub Advisory Database. Both methods return List<Vulnerability> objects. Vulnerability data can be loaded from CSV files using ResourceUtils.parseResourceAsCsv(path, Vulnerability.class, consumer) or constructed programmatically. To customize, extend DependencyVulnerabilityCheckBase and override one or both methods depending on your needs. For example, override supplementalVulnerabilities() to add custom CVEs while keeping the standard vulnerability database, or override baselineVulnerabilities() to use an entirely different vulnerability data source. Last updated: 2026-10-05T1104.
  • org.openrewrite.java.dependencies.JavaSoftwareBillOfMaterials
    • Software bill of materials for Java
    • Produces a software bill of materials (SBOM) for each Maven and Gradle project. The SBOM lists every dependency, including transitive dependencies, in the CycloneDX XML format, in a file named sbom.xml adjacent to the pom.xml or build.gradle.
  • org.openrewrite.java.dependencies.RemoveUnusedDependencies
    • Remove unused dependencies
    • Scans through source code collecting references to types and methods, removing any dependencies that are not used from Maven or Gradle build files. This is best effort and not guaranteed to work well in all cases; false positives are still possible. This recipe takes reflective access into account: - When reflective access to a class is made unambiguously via a string literal, such as: Class.forName("java.util.List") that is counted correctly. - When reflective access to a class is made ambiguously via anything other than a string literal no dependencies will be removed. This recipe takes transitive dependencies into account: - When a direct dependency is not used but a transitive dependency it brings in is in use the direct dependency is not removed.
  • org.openrewrite.java.dependencies.SoftwareBillOfMaterials
    • Software bill of materials
    • Produces a software bill of materials (SBOM) for a project. An SBOM is a complete list of all dependencies used in a project, including transitive dependencies. The produced SBOM is in the CycloneDX XML format. Supports Maven, Gradle, npm, Python, NuGet, and Go modules. Places a file named sbom.xml adjacent to the build file or package manifest, such as pom.xml, build.gradle, package.json, pyproject.toml, requirements.txt, *.csproj, packages.config, or go.mod. Manifests that share a directory, such as a pom.xml next to a package.json, contribute to the same sbom.xml.
  • org.openrewrite.java.dependencies.endoflife.FindEndOfLifeDependencies
    • Find end-of-life dependencies
    • Find Maven and Gradle dependencies whose upstream release is end-of-life or scheduled for end-of-life soon, using a snapshot of endoflife.date. Direct dependencies are marked in source; all matches (direct and transitive) are reported in the data table.
  • org.openrewrite.java.security.FindTextDirectionChanges
    • Find text-direction changes
    • Finds unicode control characters which can change the direction text is displayed in. These control characters can alter how source code is presented to a human reader without affecting its interpretation by tools like compilers. So a malicious patch could pass code review while introducing vulnerabilities. Note that text direction-changing unicode control characters aren't inherently malicious. These characters can appear for legitimate reasons in code written in or dealing with right-to-left languages. See: https://trojansource.codes/ for more information.
  • org.openrewrite.java.security.FixCommandInjectionLiteral
    • Replace Runtime.exec(String) with Runtime.exec(String[])
    • Rewrites Runtime.exec("cmd args " + arg) calls into the safer Runtime.exec(new String[]\{...\}) overload that bypasses shell interpretation. Fires only when the first argument is a string concatenation, the first operand is a string literal containing whitespace, and no literal contains shell metacharacters (|, <, >, &, ;, backtick, $, newline). Calls with no literal prefix, with single-token literals, or with shell metacharacters are left for human review.
  • org.openrewrite.java.security.FixCwe338
    • Fix CWE-338 with SecureRandom
    • Use a cryptographically strong pseudo-random number generator (PRNG).
  • org.openrewrite.java.security.FixCwe918
    • Remediate server-side request forgery (SSRF)
    • Inserts a guard that validates URLs constructed from user-controlled input do not resolve to internal, reserved, or otherwise unsafe network addresses, blocking server-side request forgery (SSRF) attacks. The block list covers IPv4 and IPv6, including IPv4-mapped IPv6 (::ffff:0:0/96), IPv6 ULA (fc00::/7), NAT64 (64:ff9b::/96), 6to4 (2002::/16), and Teredo (2001::/32) — all of which embed or translate to addresses that would otherwise bypass a naïve isSiteLocalAddress / isLoopbackAddress check. The guard does not by itself prevent DNS rebinding. URL.openConnection() re-resolves the host at connect time, so a rapidly shifting authoritative DNS response can answer with a public IP during validation and an internal IP at connect time. Closing this time-of-check / time-of-use window requires binding the TCP connection to the validated IP literal — typically via a hardened HTTP client with a custom DNS resolver (HttpClient.Builder, Apache HttpClient's DnsResolver, OkHttp's Dns, etc.) — and is HTTP-client-specific, so it is out of scope for this recipe. The block list reflects IANA special-use registries at the time of this recipe's release and is not, and cannot be, permanently complete. New special-use ranges are assigned periodically — 3fff::/20 was added as IPv6 documentation space in 2024 (RFC 9637), for example — so the list will need ongoing maintenance to keep pace with the IANA IPv4 and IPv6 Special-Purpose Address Registries.
  • org.openrewrite.java.security.FixPermissiveHostnameVerifier
    • Fix permissive HostnameVerifier implementations
    • Replaces javax.net.ssl.HostnameVerifier implementations whose verify(String, SSLSession) method unconditionally returns true (matching return true;, return Boolean.TRUE;, or return Boolean.valueOf(true);) with a delegation to HttpsURLConnection.getDefaultHostnameVerifier(), restoring proper hostname verification.
  • org.openrewrite.java.security.FixPermissiveTrustManager
    • Fix permissive X509TrustManager implementations
    • Replaces empty checkClientTrusted and checkServerTrusted method bodies on javax.net.ssl.X509TrustManager implementations with a throw new CertificateException("Not trusted") so the trust manager fails closed instead of accepting any certificate.
  • org.openrewrite.java.security.FixSqlInjectionConcat
    • Replace SQL string concatenation with a PreparedStatement
    • Rewrites JDBC Statement.executeQuery/executeUpdate/execute/addBatch calls whose argument is a string concatenation built from a literal SQL prefix plus simple variable operands into a PreparedStatement with ? placeholders and setX(i, ...) bindings. Only fixes the narrow safe subset where the Statement is a local variable from Connection.createStatement() used for a single SQL execution; other cases are left for the FindSqlInjection recipe to surface.
  • org.openrewrite.java.security.ImproperPrivilegeManagement
    • Improper privilege management
    • Marking code as privileged enables a piece of trusted code to temporarily enable access to more resources than are available directly to the code that called it.
  • org.openrewrite.java.security.JavaSecurityBestPractices
    • Java security best practices
    • Applies security best practices to Java code.
  • org.openrewrite.java.security.Owasp2025A01
    • Remediate OWASP A01:2025 Broken access control
    • OWASP A01:2025 describes failures related to broken access control.
  • org.openrewrite.java.security.Owasp2025A02
    • Remediate OWASP A02:2025 Security misconfiguration
    • OWASP A02:2025 describes failures related to security misconfiguration. Previously A05:2021, this category moved up to #2 in 2025.
  • org.openrewrite.java.security.Owasp2025A03
    • Remediate OWASP A03:2025 Software supply chain failures
    • OWASP A03:2025 describes failures related to the software supply chain, including vulnerable and outdated components. Expanded from A06:2021 Vulnerable and Outdated Components.
  • org.openrewrite.java.security.Owasp2025A04
    • Remediate OWASP A04:2025 Cryptographic failures
    • OWASP A04:2025 describes failures related to cryptography (or lack thereof), which often lead to exposure of sensitive data. Previously A02:2021.
  • org.openrewrite.java.security.Owasp2025A05
    • Remediate OWASP A05:2025 Injection
    • OWASP A05:2025 describes failures related to user-supplied data being used to influence program state to operate outside of its intended bounds. Previously A03:2021.
  • org.openrewrite.java.security.Owasp2025A07
    • Remediate OWASP A07:2025 Identification and authentication failures
    • OWASP A07:2025 describes failures related to identification and authentication, including weak credential management, missing brute force protections, session fixation, hardcoded credentials, insecure "remember me", and missing multi-factor authentication. Same position as A07:2021; recipes whose primary CWE is on the 2021 A07 mapped list are inherited from OwaspA07.
  • org.openrewrite.java.security.Owasp2025A08
    • Remediate OWASP A08:2025 Software or data integrity failures
    • OWASP A08:2025 describes failures to verify the integrity of software, code, and data artifacts across a trust boundary, including deserialization of untrusted data. Same position as A08:2021 Software and data integrity failures; the broader supply chain concerns that shared that category moved to A03:2025.
  • org.openrewrite.java.security.Owasp2025A09
    • Remediate OWASP A09:2025 Security logging and alerting failures
    • OWASP A09:2025 describes failures to detect, escalate, and alert on active attacks. Previously A09:2021 Security Logging and Monitoring Failures, renamed in 2025 to emphasize alerting. Coverage here focuses on the code-side prerequisites for effective detection: getting errors and stack traces into the log stream so SIEMs can see them, keeping user-controlled input from being able to forge log entries, and keeping secrets and other sensitive values out of the log.
  • org.openrewrite.java.security.Owasp2025A10
    • Remediate OWASP A10:2025 Mishandling of exceptional conditions
    • OWASP A10:2025 covers improper error handling: swallowed exceptions, overly broad catch/throws declarations, sensitive information leaked through error messages and stack traces, missing null checks, missing switch defaults, and omitted break statements. This is a new category in 2025.
  • org.openrewrite.java.security.OwaspA01
    • Remediate OWASP A01:2021 Broken access control
    • OWASP A01:2021 describes failures related to broken access control.
  • org.openrewrite.java.security.OwaspA02
    • Remediate OWASP A02:2021 Cryptographic failures
    • OWASP A02:2021 describes failures related to cryptography (or lack thereof), which often lead to exposure of sensitive data. This recipe seeks to remediate these vulnerabilities.
  • org.openrewrite.java.security.OwaspA03
    • Remediate OWASP A03:2021 Injection
    • OWASP A03:2021 describes failures related to user-supplied data being used to influence program state to operate outside of its intended bounds. This recipe seeks to remediate these vulnerabilities.
  • org.openrewrite.java.security.OwaspA05
    • Remediate OWASP A05:2021 Security misconfiguration
    • OWASP A05:2021 describes failures related to security misconfiguration.
  • org.openrewrite.java.security.OwaspA06
    • Remediate OWASP A06:2021 Vulnerable and outdated components
    • OWASP A06:2021 describes failures related to vulnerable and outdated components.
  • org.openrewrite.java.security.OwaspA07
    • Remediate OWASP A07:2021 Identification and authentication failures
    • OWASP A07:2021 describes failures related to identification and authentication, including weak credential management, hardcoded credentials, session fixation, weak password requirements, and anonymous LDAP binds.
  • org.openrewrite.java.security.OwaspA08
    • Remediate OWASP A08:2021 Software and data integrity failures
    • OWASP A08:2021 software and data integrity failures.
  • org.openrewrite.java.security.OwaspTopTen
    • Remediate vulnerabilities from the OWASP Top Ten
    • OWASP publishes a list of the most impactful common security vulnerabilities. These recipes identify and remediate vulnerabilities from the OWASP Top Ten.
  • org.openrewrite.java.security.OwaspTopTen2025
    • Remediate vulnerabilities from the OWASP Top Ten 2025
    • OWASP publishes a list of the most impactful common security vulnerabilities. These recipes identify and remediate vulnerabilities from the OWASP Top Ten 2025.
  • org.openrewrite.java.security.PartialPathTraversalVulnerability
    • Partial path traversal vulnerability
    • Replaces dir.getCanonicalPath().startsWith(parent.getCanonicalPath(), which is vulnerable to partial path traversal attacks, with the more secure dir.getCanonicalFile().toPath().startsWith(parent.getCanonicalFile().toPath()). To demonstrate this vulnerability, consider "/usr/outnot".startsWith("/usr/out"). The check is bypassed although /outnot is not under the /out directory. It's important to understand that the terminating slash may be removed when using various String representations of the File object. For example, on Linux, println(new File("/var")) will print /var, but println(new File("/var", "/") will print /var/; however, println(new File("/var", "/").getCanonicalPath()) will print /var.
  • org.openrewrite.java.security.RegularExpressionDenialOfService
    • Regular Expression Denial of Service (ReDOS)
    • ReDoS is a Denial of Service attack that exploits the fact that most Regular Expression implementations may reach extreme situations that cause them to work very slowly (exponentially related to input size). See the OWASP description of this attack here for more details.
  • org.openrewrite.java.security.SecureRandom
    • Secure random
    • Use cryptographically secure Pseudo Random Number Generation in the "main" source set. Replaces instantiation of java.util.Random with java.security.SecureRandom.
  • org.openrewrite.java.security.SecureRandomPrefersDefaultSeed
    • SecureRandom seeds are not constant or predictable
    • Remove SecureRandom#setSeed(*) method invocations having constant or predictable arguments.
  • org.openrewrite.java.security.SecureTempFileCreation
    • Use secure temporary file creation
    • java.io.File.createTempFile() has exploitable default file permissions. This recipe migrates to the more secure java.nio.file.Files.createTempFile().
  • org.openrewrite.java.security.UpgradeInadequateKeySize
    • Upgrade inadequate cryptographic key sizes
    • Rewrites cryptographic key-size literals that fall below current minimums. RSA/DSA/DH < 2048 bits are upgraded to 2048; EC < 224 bits are upgraded to 256 (when the algorithm is resolvable from KeyPairGenerator.getInstance(...)); symmetric (AES) < 128 bits to 128; weak named EC curves (e.g. secp112r1, prime192v1) to secp256r1. Companion fix recipe to FindInadequateKeySize. Note: changing key sizes can break interop with existing artifacts; review before applying.
  • org.openrewrite.java.security.UseFilesCreateTempDirectory
    • Use Files#createTempDirectory
    • Use Files#createTempDirectory when the sequence File#createTempFile(..)->File#delete()->File#mkdir() is used for creating a temp directory.
  • org.openrewrite.java.security.XmlParserXXEVulnerability
    • XML parser XXE vulnerability
    • Avoid exposing dangerous features of the XML parser by updating certain factory settings.
  • org.openrewrite.java.security.ZipSlip
    • Zip slip
    • Zip slip is an arbitrary file overwrite critical vulnerability, which typically results in remote command execution. A fuller description of this vulnerability is available in the Snyk documentation on it.
  • org.openrewrite.java.security.marshalling.FixInsecureJmsDeserialization
    • Restrict deserialized classes for JMS ObjectMessage
    • Patches ActiveMQConnectionFactory instantiations to install a deserialization allowlist when the same compilation run contains a javax.jms.ObjectMessage#getObject (or jakarta.jms.ObjectMessage#getObject) call inside a MessageListener#onMessage override. Targets ActiveMQ Classic (org.apache.activemq.ActiveMQConnectionFactory.setTrustedPackages) and ActiveMQ Artemis (org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory.setDeserializationAllowList). IBM MQ (com.ibm.mq.jms.MQConnectionFactory) is not yet supported. The recipe handles four factory instantiation shapes: a local variable declaration (ActiveMQConnectionFactory f = new ActiveMQConnectionFactory(...)), a direct return (return new ActiveMQConnectionFactory(...)) refactored into a declare-then-return, an assignment to an existing variable or field (this.factory = new ActiveMQConnectionFactory(...)), and a field initializer, guarded from an initializer block appended after the field. Skips factories that already configure a trusted-packages / allowlist call.
  • org.openrewrite.java.security.marshalling.InsecureJmsDeserialization
    • Insecure JMS deserialization
    • JMS Object messages depend on Java Serialization for marshalling/unmarshalling of the message payload when ObjectMessage#getObject is called. Deserialization of untrusted data can lead to security flaws.
  • org.openrewrite.java.security.marshalling.SecureJacksonDefaultTyping
    • Secure the use of Jackson default typing
    • See the blog post on this subject.
  • org.openrewrite.java.security.marshalling.SecureSnakeYamlConstructor
    • Secure the use of SnakeYAML's constructor
    • See the paper on this subject.
  • org.openrewrite.java.security.search.FindAnonymousLdapBind
    • Find anonymous LDAP binds
    • Finds JNDI environments that set Context.SECURITY_AUTHENTICATION to none or anonymous, which binds to the LDAP server without credentials and lets anyone read or modify the directory. Search only: the bind DN and password a fix needs are not present in source, and switching to simple alone leaves the bind unauthenticated.
  • org.openrewrite.java.security.search.FindBeanPropertyAssignment
    • Find Apache Commons BeanUtils property assignments
    • Finds calls to Apache Commons BeanUtils and PropertyUtils setters and bulk-copy methods (setProperty, populate, copyProperties, copyProperty, setNestedProperty, setSimpleProperty, setIndexedProperty, setMappedProperty) — including the equivalent instance-method forms on BeanUtilsBean and PropertyUtilsBean, and on any subclass of those, regardless of how the bean instance is obtained (getInstance(), new, injected field, etc.). When the property name or value flows from an untrusted source (e.g. HTTP request parameters), these calls enable bean-injection / mass-assignment (CWE-915) — an attacker can set any settable field on the bean, including ones the application never intended to expose. Per Sonar S4512 each call site needs human review for whether the property name and value come from trusted input. Detector only; does not modify code.
  • org.openrewrite.java.security.search.FindCommandInjection
    • Find OS command injection vectors
    • Finds calls to Runtime.exec(String) which passes the command through a shell interpreter, enabling command injection via metacharacters like ;, |, and &amp;&amp;. Use the String[] overload instead to avoid shell interpretation.
  • org.openrewrite.java.security.search.FindDoubleCheckedLocking
    • Find double-checked locking on a non-volatile field
    • Finds the classic double-checked locking pattern — an outer if (field == null) guarding a synchronized block that contains an inner if (field == null) \{ field = new ...(); \} — where the field is not declared volatile and the enclosing method is not synchronized. Prior to Java 5 (and still on older JVMs) another thread can observe a partially-constructed object through the outer check, skipping the lock. Prefer a synchronized accessor or the static-holder idiom; if you keep DCL, declare the field volatile.
  • org.openrewrite.java.security.search.FindExpressionLanguageInjection
    • Find Expression Language injection vectors
    • Finds calls to Expression Language (EL) evaluation methods which, when the expression is built from user input, can allow arbitrary code execution. Use parameterized expressions or input validation instead.
  • org.openrewrite.java.security.search.FindHardcodedAuthenticationCredentials
    • Find hardcoded authentication credentials
    • Finds hardcoded passwords flowing into Spring Security user builders: InMemoryUserDetailsManagerConfigurer (inMemoryAuthentication().withUser(...).password(...)) and the User.UserBuilder.password(...) API. Uses taint analysis so credentials assigned to a variable, field, or constant before being passed to .password(...) are also detected.
  • org.openrewrite.java.security.search.FindHardcodedIv
    • Find hardcoded initialization vectors
    • Finds IvParameterSpec constructed with hardcoded byte arrays or string literals. A static IV makes CBC and other modes deterministic, enabling chosen-plaintext attacks. IVs should be generated randomly using SecureRandom for each encryption operation.
  • org.openrewrite.java.security.search.FindHttpResponseSplitting
    • Find HTTP response splitting vectors
    • Finds calls to HttpServletResponse.addHeader(), setHeader(), and addCookie() which, when header values are derived from user input without CRLF sanitization, can allow HTTP response splitting attacks. Full taint-based detection requires rewrite-program-analysis; this recipe identifies the sink call sites for manual review.
  • org.openrewrite.java.security.search.FindInadequateKeySize
    • Find inadequate cryptographic key sizes
    • Finds cryptographic key generation with inadequate key sizes. RSA and DSA keys should be at least 2048 bits, EC keys at least 224 bits, and symmetric keys (AES) at least 128 bits. Weak named EC curves (e.g. secp112r1, prime192v1) are also flagged. NIST SP 800-131A Rev 2 requires RSA/DSA 2048+, EC 224+, AES 128+.
  • org.openrewrite.java.security.search.FindInsecureCipherMode
    • Find insecure cipher modes and padding schemes
    • Finds uses of Cipher.getInstance(...) whose transformation string selects an insecure mode or padding. Flags two patterns: ECB mode for any non-RSA algorithm (repeated plaintext blocks produce identical ciphertext blocks), and CBC mode with a padding scheme other than NoPadding (vulnerable to padding oracle attacks). For AES, prefer an authenticated mode such as GCM; for RSA, see FindRsaWithoutOaep.
  • org.openrewrite.java.security.search.FindInsecureRememberMeConfig
    • Find insecure Spring Security RememberMe configuration
    • Finds Spring Security RememberMe configurations with insecure settings: useSecureCookie(false) (allows cookie transmission over HTTP), alwaysRemember(true) (bypasses user opt-in), or tokenValiditySeconds(...) set longer than 30 days (extends the window in which a stolen remember-me cookie can be replayed).
  • org.openrewrite.java.security.search.FindInsecureSessionFixationConfig
    • Find Spring Security configurations that disable session fixation protection
    • Finds Spring Security configurations that disable session fixation protection by calling sessionFixation().none(). Without session fixation protection, an attacker who obtains a victim's session identifier before authentication can reuse it to hijack the authenticated session. Spring Security defaults to changeSessionId(); applications should keep that default or use migrateSession().
  • org.openrewrite.java.security.search.FindInstanceMethodStaticFieldWrite
    • Find writes to static fields from instance methods
    • Finds assignments, compound assignments (+=, -=, ...), and ++/-- operators that target a static field from inside a non-static instance method. Such writes race across instances and obscure ownership of the state; per Sonar S2696 the method should be made static or the state guarded by a thread-safe accessor.
  • org.openrewrite.java.security.search.FindInvalidJdbcIndex
    • Find invalid JDBC indices
    • Finds PreparedStatement.set...(int, ...) and ResultSet.get...(int, ...) calls whose first argument is invalid: the literal 0 (both APIs are 1-based); for PreparedStatement, an index that exceeds the number of ? placeholders in the SQL passed to Connection.prepareStatement(...) / prepareCall(...); or a for-loop counter declared starting at 0, which is a common off-by-one against JDBC's 1-based indexing. Each mistake throws SQLException at runtime.
  • org.openrewrite.java.security.search.FindJacksonDefaultTypeMapping
    • Find Jackson default type mapping enablement
    • ObjectMapper#enableTypeMapping(..) can lead to vulnerable deserialization.
  • org.openrewrite.java.security.search.FindJdbcEmptyPassword
    • Find JDBC connections with empty passwords
    • Finds DriverManager.getConnection(...) calls whose password argument is empty or whitespace-only, or whose URL embeds a password= query parameter with no value. Connecting to a database without a password grants unauthenticated access; the password should be sourced from configuration or a secret manager instead.
  • org.openrewrite.java.security.search.FindLogInjection
    • Find log injection vulnerabilities
    • Finds logging statements where HTTP request input flows unsanitized into the log argument, allowing attackers to inject forged log entries via CRLF injection (CWE-117). Sources are servlet request accessors (getParameter, getHeader, getReader, getInputStream, etc.), Spring WebRequest accessors, and Spring MVC handler parameters bound with @RequestParam, @PathVariable, @RequestHeader, @RequestBody, @RequestPart, @CookieValue, or @MatrixVariable. Uses taint analysis so input assigned to a variable, field, or built into a larger string before being logged is also detected.
  • org.openrewrite.java.security.search.FindLongSessionTimeout
    • Find long or disabled HTTP session timeout
    • Finds calls to HttpSession.setMaxInactiveInterval(int) whose integer-literal argument exceeds 30 minutes or is zero/negative (which disables session expiration). Long-lived or non-expiring sessions increase the window for session hijacking and replay (CWE-613).
  • org.openrewrite.java.security.search.FindMassAssignment
    • Find mass assignment
    • Finds Spring and JAX-RS handler method parameters whose type is a JPA @Entity. The framework populates every property of the object from the request, so a client can set fields the form never exposes, such as a password or a role, and the entity is then persisted (CWE-915). Search only: the fix is a DTO plus a mapping layer.
  • org.openrewrite.java.security.search.FindMissingSpringAuthorization
    • Find Spring MVC handlers missing authorization
    • Flags Spring MVC (and WebFlux) controller methods reachable to anonymous users — either matched by permitAll() in a SecurityFilterChain / SecurityWebFilterChain bean (or in a legacy WebSecurityConfigurerAdapter.configure(HttpSecurity) override) or with no matching rule at all — and which do not carry an explicit authorization annotation (@PreAuthorize, @PostAuthorize, @Secured, @RolesAllowed, @PermitAll, @DenyAll), including annotations inherited from a superclass or overridden parent method. Security rules are read from both the Java fluent API (requestMatchers(...).permitAll()) and the Kotlin DSL (authorize(&quot;/path&quot;, permitAll)). Detector only; does not modify code.
  • org.openrewrite.java.security.search.FindPermissiveCorsConfiguration
    • Find permissive CORS configuration
    • Finds overly permissive CORS configurations that allow all origins, which can expose the application to cross-domain attacks.
  • org.openrewrite.java.security.search.FindPredictableSalt
    • Find predictable cryptographic salts
    • Finds PBEParameterSpec and PBEKeySpec constructed with hardcoded or too-short salt byte arrays. A predictable salt undermines the purpose of salting, making rainbow table and precomputation attacks feasible; a salt shorter than 16 bytes is below the minimum strength recommended by NIST SP 800-132. Salts should be generated randomly using SecureRandom and at least 16 bytes long.
  • org.openrewrite.java.security.search.FindProcessControl
    • Find process control vectors
    • Finds calls to System.loadLibrary(), System.load(), and Runtime.load() which, when the library path or name is derived from user input, can allow an attacker to load arbitrary native code. Ensure library names are not externally controlled.
  • org.openrewrite.java.security.search.FindPubliclyWritableTempDirectory
    • Find publicly writable temporary directories
    • Finds hardcoded paths into publicly writable directories such as /tmp passed to file APIs, reads of the TMP, TMPDIR and TEMP environment variables or java.io.tmpdir, and temporary files or directories created in the default location. Likely test code is skipped. Search only: whether a shared directory is exploitable depends on deployment.
  • org.openrewrite.java.security.search.FindResourceInjection
    • Find resource injection vectors
    • Detects resource injection vulnerabilities where user-controlled input flows to resource access operations — file paths, JNDI lookups, class loading, and native library loading. Uses taint analysis from rewrite-program-analysis for source-to-sink tracking with sanitizer support, plus structural detection as fallback.
  • org.openrewrite.java.security.search.FindRsaWithoutOaep
    • Find RSA encryption without OAEP padding
    • Finds uses of RSA encryption with PKCS#1 v1.5 padding or no padding specification. RSA without OAEP padding is vulnerable to padding oracle attacks. Use RSA/ECB/OAEPWithSHA-256AndMGF1Padding or equivalent OAEP mode instead.
  • org.openrewrite.java.security.search.FindScriptEngineInjection
    • Find script engine code injection vectors
    • Finds calls to ScriptEngine.eval() which can execute arbitrary code if the script string is influenced by user input. Consider sandboxing or removing dynamic script evaluation.
  • org.openrewrite.java.security.search.FindSensitiveApiEndpoints
    • Find sensitive API endpoints
    • Find data models exposed by REST APIs that contain sensitive information like PII and secrets.
  • org.openrewrite.java.security.search.FindSensitiveDataInLogs
    • Find sensitive data in log statements
    • Finds logging statements where arguments include variables, fields, or method calls with names that suggest sensitive data (passwords, tokens, SSNs, credit card numbers, etc.). Logging sensitive data can lead to information disclosure through log files (CWE-532).
  • org.openrewrite.java.security.search.FindSqlInjection
    • Find potential SQL injection
    • Finds SQL query methods where the query string is constructed via string concatenation, which may indicate SQL injection vulnerabilities. Use parameterized queries or prepared statements instead.
  • org.openrewrite.java.security.search.FindThreadSleepInSynchronized
    • Find Thread.sleep(...) calls while holding a monitor
    • Finds Thread.sleep(...) calls whose nearest enclosing frame is a synchronized (...) block or a synchronized method. Sleeping while holding a monitor keeps every other thread that needs the same lock blocked until the sleep completes; Object.wait(...) releases the monitor for the duration and reacquires it on return.
  • org.openrewrite.java.security.search.FindUnsafeReflection
    • Find unsafe reflection vectors
    • Finds calls to Class.forName() which, when the class name is derived from user input, can allow an attacker to instantiate arbitrary classes. Review these call sites to ensure the class name is not externally controlled.
  • org.openrewrite.java.security.search.FindUnsignedJwt
    • Find unsigned JWT usage
    • Finds construction or parsing of Nimbus PlainJWT — an unsecured JWT that has no signature or MAC. Unsecured JWTs allow an attacker to forge tokens because their payloads are not integrity-protected. Use a signed (SignedJWT) or encrypted (EncryptedJWT) JWT instead.
  • org.openrewrite.java.security.search.FindUserWithDefaultPasswordEncoder
    • Find User.withDefaultPasswordEncoder() usage
    • Flags any call to User.withDefaultPasswordEncoder() from Spring Security. The factory is documented as for non-production demos only: it stores credentials in memory with a fixed encoder and is unsafe for real workloads.
  • org.openrewrite.java.security.search.FindVulnerableJacksonJsonTypeInfo
    • Find vulnerable uses of Jackson @JsonTypeInfo
    • Identify where attackers can deserialize gadgets into a target field.
  • org.openrewrite.java.security.search.FindWaitNotifyOnThread
    • Find wait/notify/notifyAll called on a Thread instance
    • Finds invocations of Object.wait(...), Object.notify(), or Object.notifyAll() whose receiver is a java.lang.Thread (or subtype), including bare invocations inside a Thread subclass method that implicitly target this. The JVM uses a Thread instance's monitor internally to change thread state (BLOCKED, WAITING, etc.); calling these methods on a Thread can corrupt that state. Use a dedicated lock object as the monitor instead.
  • org.openrewrite.java.security.search.FindWeakCryptoAlgorithm
    • Find weak cryptographic algorithms
    • Finds uses of broken or risky cryptographic algorithms such as MD5, SHA-1, DES, DESede (3DES), RC2, RC4, and Blowfish in calls to Cipher.getInstance(), MessageDigest.getInstance(), Mac.getInstance(), KeyGenerator.getInstance(), and SecretKeyFactory.getInstance(). Also flags instantiation of javax.crypto.NullCipher, which performs no encryption.
  • org.openrewrite.java.security.search.FindWeakDigestInPasswordEncoder
    • Find weak message digests used inside custom PasswordEncoder implementations
    • Finds calls to MessageDigest.getInstance(&quot;...&quot;) whose algorithm is unsuitable for password storage, scoped to classes implementing org.springframework.security.crypto.password.PasswordEncoder. Unsalted and non-iterated digests (MD2, MD4, MD5, SHA-1, SHA-224/256/384/512) are unsuitable for password hashing regardless of how they are wrapped. Delegate to BCryptPasswordEncoder, Argon2PasswordEncoder, Pbkdf2PasswordEncoder, or SCryptPasswordEncoder instead of implementing PasswordEncoder yourself.
  • org.openrewrite.java.security.search.FindWeakPasswordEncoderStrength
    • Find weak password encoder strength
    • Finds Spring Security BCryptPasswordEncoder instantiations with a strength (work factor) below 10. The default and OWASP-recommended minimum is 10; lower values make stolen password hashes substantially cheaper to brute-force.
  • org.openrewrite.java.security.search.FindWeakPasswordHashing
    • Find weak password hashing
    • Finds uses of MessageDigest.getInstance() with algorithms unsuitable for password hashing (MD5, SHA-1, SHA-256, SHA-384, SHA-512). Passwords should be hashed with a purpose-built password hashing function such as bcrypt, scrypt, Argon2, or PBKDF2 that includes a salt and a tunable work factor.
  • org.openrewrite.java.security.search.FindWeakSpringPasswordEncoder
    • Find weak Spring Security password encoders
    • Finds uses of Spring Security password encoders that are unsuitable for production password storage: NoOpPasswordEncoder (plaintext), StandardPasswordEncoder (deprecated SHA-256), MessageDigestPasswordEncoder (raw message digest), Md4PasswordEncoder (MD4, broken), LdapShaPasswordEncoder (deprecated), Md5PasswordEncoder and ShaPasswordEncoder (from the deprecated authentication.encoding package), and SCryptPasswordEncoder (deprecated in current Spring Security). Use an adaptive function such as BCryptPasswordEncoder, Argon2PasswordEncoder, or Pbkdf2PasswordEncoder instead.
  • org.openrewrite.java.security.search.FindWeakTlsProtocol
    • Find weak SSL/TLS protocols
    • Finds deprecated SSL and TLS protocol versions (SSL 1.0 through 3.0, TLS 1.0 and 1.1) requested through SSLContext.getInstance(), setEnabledProtocols(), SSLParameters.setProtocols(), or OkHttp's tlsVersions(). Search only: a safe replacement depends on the JRE and the peer, neither visible in source.
  • org.openrewrite.java.security.search.FindXPathInjection
    • Find XPath injection vectors
    • Finds calls to XPath.evaluate() and XPath.compile() which, when the expression is built from user input, can allow XPath injection attacks. Use parameterized XPath expressions or input validation instead.
  • org.openrewrite.java.security.secrets.FindArtifactorySecrets
    • Find Artifactory secrets
    • Locates Artifactory secrets stored in plain text in code.
  • org.openrewrite.java.security.secrets.FindAwsSecrets
    • Find AWS secrets
    • Locates AWS secrets stored in plain text in code.
  • org.openrewrite.java.security.secrets.FindAzureSecrets
    • Find Azure secrets
    • Locates Azure secrets stored in plain text in code.
  • org.openrewrite.java.security.secrets.FindBasicAuthSecrets
    • Find HTTP Basic authentication secrets
    • Locates HTTP Basic authentication credentials stored in plain text in code.
  • org.openrewrite.java.security.secrets.FindBearerTokenSecrets
    • Find Bearer token secrets
    • Locates HTTP Bearer tokens (RFC 6750) stored in plain text in code.
  • org.openrewrite.java.security.secrets.FindDiscordSecrets
    • Find Discord secrets
    • Locates Discord secrets stored in plain text in code.
  • org.openrewrite.java.security.secrets.FindFacebookSecrets
    • Find Facebook secrets
    • Locates Facebook secrets stored in plain text in code.
  • org.openrewrite.java.security.secrets.FindGenericSecrets
    • Find generic secrets
    • Locates generic secrets stored in plain text in code.
  • org.openrewrite.java.security.secrets.FindGitHubSecrets
    • Find GitHub secrets
    • Locates GitHub secrets stored in plain text in code.
  • org.openrewrite.java.security.secrets.FindGoogleSecrets
    • Find Google secrets
    • Locates Google secrets stored in plain text in code.
  • org.openrewrite.java.security.secrets.FindHerokuSecrets
    • Find Heroku secrets
    • Locates Heroku secrets stored in plain text in code.
  • org.openrewrite.java.security.secrets.FindJwtSecrets
    • Find JWT secrets
    • Locates JWTs stored in plain text in code.
  • org.openrewrite.java.security.secrets.FindMailChimpSecrets
    • Find MailChimp secrets
    • Locates MailChimp secrets stored in plain text in code.
  • org.openrewrite.java.security.secrets.FindMailgunSecrets
    • Find Mailgun secrets
    • Locates Mailgun secrets stored in plain text in code.
  • org.openrewrite.java.security.secrets.FindNpmSecrets
    • Find NPM secrets
    • Locates NPM secrets stored in plain text in code.
  • org.openrewrite.java.security.secrets.FindPasswordInUrlSecrets
    • Find passwords used in URLs
    • Locates URLs that contain passwords in plain text.
  • org.openrewrite.java.security.secrets.FindPayPalSecrets
    • Find PayPal secrets
    • Locates PayPal secrets stored in plain text in code.
  • org.openrewrite.java.security.secrets.FindPgpSecrets
    • Find PGP secrets
    • Locates PGP secrets stored in plain text in code.
  • org.openrewrite.java.security.secrets.FindPicaticSecrets
    • Find Picatic secrets
    • Locates Picatic secrets stored in plain text in code.
  • org.openrewrite.java.security.secrets.FindRsaSecrets
    • Find RSA private keys
    • Locates RSA private keys stored in plain text in code.
  • org.openrewrite.java.security.secrets.FindSecrets
    • Find secrets
    • Locates secrets stored in plain text in code.
  • org.openrewrite.java.security.secrets.FindSecretsByPattern
    • Find secrets with regular expressions
    • A secret is a literal that matches any one of the provided patterns.
  • org.openrewrite.java.security.secrets.FindSendGridSecrets
    • Find SendGrid secrets
    • Locates SendGrid secrets stored in plain text in code.
  • org.openrewrite.java.security.secrets.FindSlackSecrets
    • Find Slack secrets
    • Locates Slack secrets stored in plain text in code.
  • org.openrewrite.java.security.secrets.FindSquareSecrets
    • Find Square secrets
    • Locates Square secrets stored in plain text in code.
  • org.openrewrite.java.security.secrets.FindSshSecrets
    • Find SSH secrets
    • Locates SSH secrets stored in plain text in code.
  • org.openrewrite.java.security.secrets.FindStripeSecrets
    • Find Stripe secrets
    • Locates Stripe secrets stored in plain text in code.
  • org.openrewrite.java.security.secrets.FindTelegramSecrets
    • Find Telegram secrets
    • Locates Telegram secrets stored in plain text in code.
  • org.openrewrite.java.security.secrets.FindTwilioSecrets
    • Find Twilio secrets
    • Locates Twilio secrets stored in plain text in code.
  • org.openrewrite.java.security.secrets.FindTwitterSecrets
    • Find Twitter secrets
    • Locates Twitter secrets stored in plain text in code.
  • org.openrewrite.java.security.servlet.CookieSetHttpOnly
    • Cookies missing HttpOnly flag
    • Check for use of cookies without the HttpOnly flag. Cookies should be marked as HttpOnly to prevent client-side scripts from accessing them, reducing the risk of cross-site scripting (XSS) attacks.
  • org.openrewrite.java.security.servlet.CookieSetSecure
    • Insecure cookies
    • Check for use of insecure cookies. Cookies should be marked as secure. This ensures that the cookie is sent only over HTTPS to prevent cross-site scripting attacks.
  • org.openrewrite.java.security.spring.CsrfProtection
    • Enable CSRF attack prevention
    • Cross-Site Request Forgery (CSRF) is a type of attack that occurs when a malicious web site, email, blog, instant message, or program causes a user's web browser to perform an unwanted action on a trusted site when the user is authenticated. See the full OWASP cheatsheet.
  • org.openrewrite.java.security.spring.InsecureSpringServiceExporter
    • Secure Spring service exporters
    • The default Java deserialization mechanism is available via ObjectInputStream class. This mechanism is known to be vulnerable. If an attacker can make an application deserialize malicious data, it may result in arbitrary code execution. Spring’s RemoteInvocationSerializingExporter uses the default Java deserialization mechanism to parse data. As a result, all classes that extend it are vulnerable to deserialization attacks. The Spring Framework contains at least HttpInvokerServiceExporter and SimpleHttpInvokerServiceExporter that extend RemoteInvocationSerializingExporter. These exporters parse data from the HTTP body using the unsafe Java deserialization mechanism. See the full blog post by Artem Smotrakov on CVE-2016-1000027 from which the above description is excerpted.
  • org.openrewrite.java.security.spring.PreventClickjacking
    • Prevent clickjacking
    • The frame-ancestors directive can be used in a Content-Security-Policy HTTP response header to indicate whether or not a browser should be allowed to render a page in a &lt;frame&gt; or &lt;iframe&gt;. Sites can use this to avoid Clickjacking attacks by ensuring that their content is not embedded into other sites.
  • org.openrewrite.java.security.spring.RemoveEnableWebSecurityDebug
    • Remove debug mode from Spring Security
    • Removes the debug attribute from @EnableWebSecurity annotations to prevent sensitive security information from being logged in production.
  • org.openrewrite.java.security.xss.FixXssVulnerability
    • Fix XSS vulnerabilities
    • Aggregates the cross-site scripting (CWE-79) fixes. Covers Java sources that flow user-controlled values into HTML output sinks (via FixXssVulnerabilityJava, which consumes the same taint spec as FindXssVulnerability), JSP scriptlets that read directly from request parameters or headers, and Thymeleaf templates that use the unescaped th:utext attribute.
  • org.openrewrite.java.security.xss.FixXssVulnerabilityJsp
    • Replace XSS-prone JSP scriptlets with &lt;c:out&gt;
    • Replaces &lt;%= request.getParameter(&quot;x&quot;) %&gt; and &lt;%= request.getHeader(&quot;x&quot;) %&gt; scriptlets in JSP files with the equivalent escaped &lt;c:out value=&quot;$\{param.x\}&quot;/&gt; / &lt;c:out value=&quot;$\{header['x']\}&quot;/&gt; tags, and inserts the JSTL core taglib at the top of the file if not already declared. Only fires on string-literal argument forms — arbitrary expressions inside &lt;%= ... %&gt; are left untouched for human review. Note: request.getParameter returns null for missing parameters and prints &quot;null&quot;, whereas $\{param.x\} renders empty; review templates that rely on the literal string &quot;null&quot;.
  • org.openrewrite.java.security.xss.ReplaceThymeleafUnescaped
    • Replace th:utext with th:text in Thymeleaf templates
    • Replaces Thymeleaf's unescaped attribute th:utext (and data-th-utext) with its escaped equivalent th:text (data-th-text) in .html / .htm template files. th:utext interpolates raw HTML and is the canonical Thymeleaf XSS sink. The recipe only fires on files that look like Thymeleaf templates (declare the xmlns:th namespace or use a th: / data-th- attribute somewhere). If you have a legitimate raw-HTML interpolation, restore it manually and rely on Thymeleaf's [# th:utext] block syntax or a sanitized model attribute.
  • org.openrewrite.node.dependencies.FindEndOfLifeDependencies
    • Find end-of-life npm dependencies
    • Find npm dependencies whose upstream release is end-of-life or scheduled for end-of-life soon, using a snapshot of endoflife.date. Direct dependencies declared in package.json are marked in source; all matches (direct and transitive) are reported in the data table.
  • org.openrewrite.node.dependencies.SoftwareBillOfMaterials
    • Software bill of materials for JavaScript
    • Produces a software bill of materials (SBOM) for each npm package. The SBOM lists every production dependency, including transitive dependencies resolved from the lock file, in the CycloneDX XML format, in a file named sbom.xml adjacent to the package.json.
  • org.openrewrite.python.dependencies.DependencyVulnerabilityCheck
    • Find and fix vulnerable PyPI dependencies
    • This software composition analysis (SCA) tool detects and upgrades dependencies with publicly disclosed vulnerabilities. This recipe both generates a report of vulnerable dependencies and upgrades to newer versions with fixes. This recipe by default only upgrades to the latest patch version. If a minor or major upgrade is required to reach the fixed version, this can be controlled using the maximumUpgradeDelta option. Vulnerability information comes from the GitHub Security Advisory Database, which aggregates vulnerability data from several public databases, including the National Vulnerability Database maintained by the United States government. Dependencies following Semantic Versioning will see their patch version updated where applicable. ## Customizing Vulnerability Data This recipe can be customized by extending DependencyVulnerabilityCheckBase and overriding the vulnerability data sources: - baselineVulnerabilities(ExecutionContext ctx): Provides the default set of known vulnerabilities. The base implementation loads vulnerability data from the GitHub Security Advisory Database CSV file using ResourceUtils.parseResourceAsCsv(). Override this method to replace the entire vulnerability dataset with your own curated list. - supplementalVulnerabilities(ExecutionContext ctx): Allows adding custom vulnerability data beyond the baseline. The base implementation returns an empty list. Override this method to add organization-specific vulnerabilities, internal security advisories, or vulnerabilities from additional sources while retaining the baseline GitHub Advisory Database. Both methods return List&lt;Vulnerability&gt; objects. Vulnerability data can be loaded from CSV files using ResourceUtils.parseResourceAsCsv(path, Vulnerability.class, consumer) or constructed programmatically. To customize, extend DependencyVulnerabilityCheckBase and override one or both methods depending on your needs. For example, override supplementalVulnerabilities() to add custom CVEs while keeping the standard vulnerability database, or override baselineVulnerabilities() to use an entirely different vulnerability data source.
  • org.openrewrite.python.dependencies.SoftwareBillOfMaterials
    • Software bill of materials for Python
    • Produces a software bill of materials (SBOM) for each Python project. The SBOM lists every runtime dependency, including transitive dependencies resolved from the lock file, in the CycloneDX XML format, in a file named sbom.xml adjacent to the pyproject.toml, requirements.txt, or other Python manifest.
  • org.openrewrite.recipe.rewrite-java-security.InlineDeprecatedMethods
    • Inline deprecated delegating methods
    • Automatically generated recipes to inline deprecated method calls that delegate to other methods in the same class.
  • org.openrewrite.text.FindHardcodedLoopbackAddresses
    • Find hard-coded loopback IPv4 addresses
    • Locates mentions of hard-coded IPv4 addresses from the loopback IP range. The loopback IP range includes 127.0.0.0 to 127.255.255.255. This detects the entire localhost/loopback subnet range, not just the commonly used 127.0.0.1.
  • org.openrewrite.text.FindHardcodedPrivateIPAddresses
    • Find hard-coded private IPv4 addresses
    • Locates mentions of hard-coded IPv4 addresses from private IP ranges. Private IP ranges include: * 192.168.0.0 to 192.168.255.255 * 10.0.0.0 to 10.255.255.255 * 172.16.0.0 to 172.31.255.255 It is not detecting the localhost subnet 127.0.0.0 to 127.255.255.255.
  • org.openrewrite.text.RemoveHardcodedIPAddressesFromComments
    • Remove hard-coded IP addresses from comments
    • Removes hard-coded IPv4 addresses from comments when they match private IP ranges or loopback addresses. This targets IP addresses that are commented out in various comment formats: Private IP ranges: * 192.168.0.0 to 192.168.255.255 * 10.0.0.0 to 10.255.255.255 * 172.16.0.0 to 172.31.255.255 Loopback IP range: * 127.0.0.0 to 127.255.255.255 Supported comment formats: * C-style line comments (//) * C-style block comments (/* */) * Shell/Python style comments (#) * XML comments (&lt;!-- --&gt;) * YAML comments (#) * Properties file comments (# or !) For line comments, the entire line is removed. For block comments, only the IP address is removed.

rewrite-jenkins​

License: Moderne Source Available License

19 recipes

rewrite-joda​

License: Moderne Source Available License

13 recipes

rewrite-kubernetes​

License: Moderne Proprietary License

107 recipes

  • io.moderne.kubernetes.sylva.migrate.dasschiff.FindBgpPeeringMigrationBlockers
    • Find what blocks a Das Schiff BGPPeering from moving to the Sylva network connector API
    • Report what a human has to decide before a Das Schiff BGPPeering can move to the network-connector.sylvaproject.org group. Nothing is rewritten: the legacy spec.export is a reject-by-default prefix filter and the intent one is accept-by-default BGP communities, so a peering moved as it stands would advertise the whole VRF table.
  • io.moderne.kubernetes.sylva.migrate.dasschiff.FindDasSchiffMigrationWork
    • Find Das Schiff resources that have to move to Sylva
    • Inventory every Das Schiff resource the Sylva intent group replaces and report, per kind, whether it moves automatically or what has to be decided first. All eight legacy kinds are marked, the three the operator generates included, so a kind that goes unmentioned is one this catalogue does not know about. A repository partway through the move also reports where the intent resources it already holds no longer say what the legacy ones do. Reports only; nothing is rewritten.
  • io.moderne.kubernetes.sylva.migrate.dasschiff.FindIntentMigrationDrift
    • Find drift between Das Schiff and Sylva intent network resources
    • Compare the network.t-caas.telekom.com resources in a repository against the network-connector.sylvaproject.org resources meant to replace them, and report every field the two no longer agree on. They are paired by VRF name and VLAN id, so a hand written translation is checked as readily as a generated one.
  • io.moderne.kubernetes.sylva.migrate.dasschiff.FindLegacyTCaasNetworkResources
    • Find legacy T-CaaS network resources
    • Find resources still on the legacy network.t-caas.telekom.com group and report what supersedes each in network-connector.sylvaproject.org. No kind moves on apiVersion alone, not even BGPPeering, which exists in both groups under the same name but shares only four fields.
  • io.moderne.kubernetes.sylva.migrate.dasschiff.FindLowLevelNetworkConfig
    • Find VRFRouteConfiguration and Layer2NetworkConfiguration to migrate
    • Find the Das Schiff VRFRouteConfiguration and Layer2NetworkConfiguration resources the Sylva intent group replaces, and report for each whether it moves automatically or why it has to be moved by hand. Resources that do move also report the fields the intent group derives rather than stores, which are the ones worth re-reading in review.
  • io.moderne.kubernetes.sylva.migrate.dasschiff.FindMirrorConfig
    • Find Das Schiff traffic mirror configuration
    • Find the Das Schiff MirrorTarget and MirrorSelector resources the Sylva Collector and TrafficMirror replace, and report for each whether it moves automatically or why it has to be moved by hand. Reports only; nothing is rewritten.
  • io.moderne.kubernetes.sylva.migrate.dasschiff.FindNetworkOperatorConfigMap
    • Find Das Schiff network operator ConfigMaps
    • Inventory the ConfigMaps that configure Das Schiff's network operator, reporting for each data key how the value is written and how large it is. Each key is a whole embedded document the operator hands to its node agents as a file, not a setting. Nothing here reads those documents, so the report holds for any version of them.
  • io.moderne.kubernetes.sylva.migrate.dasschiff.FindUnclassifiedExportRanges
    • Find unclassified Das Schiff export ranges
    • Report every VRFRouteConfiguration.spec.export range that has to be classified as a load balancer pool or an egress NAT pool before an Inbound or Outbound can be generated for it. Nothing in the legacy group tells the two apart.
  • io.moderne.kubernetes.sylva.migrate.dasschiff.GenerateInboundAndOutboundFromExportRanges
    • Generate Inbound and Outbound from export ranges
    • Generate a Sylva Inbound or Outbound for each VRFRouteConfiguration.spec.export range the classifications option names as a load balancer pool or an egress NAT pool. Nothing in the legacy group tells the two apart, so an unclassified range is reported and left alone rather than guessed at.
  • io.moderne.kubernetes.sylva.migrate.dasschiff.MigrateLowLevelNetworkConfigToIntent
    • Migrate VRFRouteConfiguration and Layer2NetworkConfiguration to Sylva
    • Rewrite Das Schiff VRFRouteConfiguration and Layer2NetworkConfiguration resources into the network-connector.sylvaproject.org intent resources that replace them. Each becomes two: a VRF and a Destination, or a Network and a Layer2Attachment. Both kinds move here rather than in a recipe each, because a VRF moves whole or not at all. A resource whose meaning would change is reported rather than approximated.
  • io.moderne.kubernetes.sylva.migrate.dasschiff.MigrateMirrorConfigToIntent
    • Migrate Das Schiff traffic mirror configuration to intent resources
    • Rewrite Das Schiff MirrorTarget and MirrorSelector resources into the Collector and TrafficMirror that replace them. A Collector repeats its loopback's subnet inline, so a target whose mirror VRF is not declared in the same manifest is reported rather than moved.
  • io.moderne.kubernetes.sylva.migrate.dasschiff.MigrateTCaasToSylvaNetworkConnector
    • Migrate T-CaaS network resources to the Sylva network connector API
    • Move what can be moved without a decision from Das Schiff's low level network.t-caas.telekom.com group onto the network-connector.sylvaproject.org intent group. Four of the eight legacy kinds move: VRFRouteConfiguration and Layer2NetworkConfiguration together rather than one at a time, because a VRF whose attachment stays behind stops advertising that attachment's subnet, and MirrorTarget and MirrorSelector likewise, because a selector without its collector points at nothing. BGPPeering is report-only. NodeNetworkConfig, NodeNetplanConfig and NetworkConfigRevision are operator output rather than input — the first two are named after a node and owned by it, the third by a hash of its own spec — so their absence is not a gap.
  • io.moderne.kubernetes.sylva.migrate.dasschiff.MigrateVrfRouteConfigurationCommunityToCommunities
    • Migrate VRFRouteConfiguration community to communities
    • Promote the deprecated scalar spec.community of a Das Schiff VRFRouteConfiguration to the spec.communities sequence that replaces it. The operator's webhook rejects a resource that sets both, so one that already does is reported rather than merged.
  • org.openrewrite.kubernetes.AddConfiguration
    • Add Kubernetes configuration
    • Add default required configuration when it is missing.
  • org.openrewrite.kubernetes.AddPodSpecConfiguration
    • Add Kubernetes pod spec configuration
    • Add default required configuration to a workload's pod spec when it is missing. The pod spec is located by kind, so a Deployment, StatefulSet, DaemonSet, ReplicaSet, ReplicationController, Job or CronJob is configured as well as a bare Pod.
  • org.openrewrite.kubernetes.ChangeApiVersion
    • Change Kubernetes API version
    • Change the Kubernetes API version in a resource.
  • org.openrewrite.kubernetes.ImagePullPolicyAlways
    • Ensure image pull policy is Always
    • Ensures the latest version of a tag is deployed each time.
  • org.openrewrite.kubernetes.KubernetesBestPractices
    • Kubernetes best practices
    • Applies best practices to Kubernetes manifests.
  • org.openrewrite.kubernetes.LifecycleRuleOnStorageBucket
    • Ensure lifecycle rule on StorageBucket
    • When defining a rule, you can specify any set of conditions for any action. The following configuration defines a rule to delete all objects older than 7 days in a bucket.
  • org.openrewrite.kubernetes.LimitContainerCapabilities
    • Limit root capabilities in a container
    • Limiting the admission of containers with capabilities ensures that only a small number of containers have extended capabilities outside the default range.
  • org.openrewrite.kubernetes.MissingCpuLimits
    • Ensure CPU limits are set
    • A system without managed quotas could eventually collapse due to inadequate resources for the tasks it bares.
  • org.openrewrite.kubernetes.MissingCpuRequest
    • Ensure CPU request is set
    • If a container is created in a namespace that has a default CPU limit, and the container does not specify its own CPU limit, then the container is assigned the default CPU limit.
  • org.openrewrite.kubernetes.MissingMemoryLimits
    • Ensure memory limits are set
    • With no limit set, kubectl allocates more and more memory to the container until it runs out.
  • org.openrewrite.kubernetes.MissingMemoryRequest
    • Ensure memory request is set
    • A container is guaranteed to have as much memory as it requests, but is not allowed to use more memory than the limit set. This configuration may save resources and prevent an attack on an exploited container.
  • org.openrewrite.kubernetes.MissingPodLivenessProbe
    • Ensure liveness probe is configured
    • The kubelet uses liveness probes to know when to schedule restarts for containers. Restarting a container in a deadlock state can help to make the application more available, despite bugs.
  • org.openrewrite.kubernetes.MissingPodReadinessProbe
    • Ensure readiness probe is configured
    • Using the Readiness Probe ensures teams define what actions need to be taken to prevent failure and ensure recovery in case of unexpected errors.
  • org.openrewrite.kubernetes.NoHostIPCSharing
    • No host IPC sharing
    • Preventing sharing of host PID/IPC namespace, networking, and ports ensures proper isolation between Docker containers and the underlying host.
  • org.openrewrite.kubernetes.NoHostNetworkSharing
    • No host network sharing
    • When using the host network mode for a container, that container’s network stack is not isolated from the Docker host, so the container shares the host’s networking namespace and does not get its own IP-address allocation.
  • org.openrewrite.kubernetes.NoHostProcessIdSharing
    • No host process ID sharing
    • Sharing the host process ID namespace breaks the isolation between container images and can make processes visible to other containers in the pod. This includes all information in the /proc directory, which can sometimes include passwords or keys, passed as environment variables.
  • org.openrewrite.kubernetes.NoPrivilegeEscalation
    • No privilege escalation
    • Does not allow a process to gain more privileges than its parent process.
  • org.openrewrite.kubernetes.NoPrivilegedContainers
    • No privileged containers
    • Privileged containers are containers that have all of the root capabilities of a host machine, allowing access to resources that are not accessible in ordinary containers.
  • org.openrewrite.kubernetes.NoRootContainers
    • No root containers
    • Containers that run as root frequently have more permissions than their workload requires which, in case of compromise, could help an attacker further their exploits.
  • org.openrewrite.kubernetes.ReadOnlyRootFilesystem
    • Read-only root filesystem
    • Using an immutable root filesystem and a verified boot mechanism prevents against attackers from "owning" the machine through permanent local changes.
  • org.openrewrite.kubernetes.UpdateContainerImageName
    • Update image name
    • Search for image names that match patterns and replace the components of the name with new values.
  • org.openrewrite.kubernetes.clusterapi.MigrateAwsProviderToV1beta2
    • Migrate Cluster API Provider AWS resources to v1beta2
    • Change the apiVersion of the resources served by Cluster API Provider AWS to v1beta2, across the infrastructure, bootstrap and controlplane groups it contributes to. ROSA* and Nodeadm* are absent because they were introduced at v1beta2 and never had a v1beta1. This recipe changes apiVersion only. Whatever else this provider reshaped in v1beta2 is defined by the provider rather than by the Cluster API contract, so review the resources it touches against the provider's own migration notes.
  • org.openrewrite.kubernetes.clusterapi.MigrateClusterApiCoreResourceToV1beta2
    • Migrate the Cluster API core group to v1beta2
    • Rewrite cluster.x-k8s.io/v1beta1 resources into their v1beta2 form, fields and apiVersion together. v1beta1 has been deprecated since Cluster API v1.11 and stops being served in v1.16. A resource moves as a whole or not at all: where v1beta2 dropped a field outright, or a duration cannot be read exactly, it stays on v1beta1 and the reason is reported.
  • org.openrewrite.kubernetes.clusterapi.MigrateClusterApiCoreToV1beta2
    • Migrate the Cluster API core group to v1beta2
    • Rewrite every cluster.x-k8s.io/v1beta1 resource Cluster API owns into its v1beta2 form, fields and apiVersion together. v1beta1 has been deprecated since Cluster API v1.11 and stops being served in v1.16. To migrate a subset, compose your own list from the per-kind recipes below.
  • org.openrewrite.kubernetes.clusterapi.MigrateClusterClassToV1beta2
    • Migrate ClusterClass to cluster.x-k8s.io/v1beta2
    • Rewrite a ClusterClass into its v1beta2 form. Templates are named through templateRef without the template wrapper. A templateRef still carries an apiVersion, so which are safe to re-point belongs to the provider serving each kind and is reported rather than guessed.
  • org.openrewrite.kubernetes.clusterapi.MigrateClusterToV1beta2
    • Migrate Cluster to cluster.x-k8s.io/v1beta2
    • Rewrite a Cluster into its v1beta2 form. spec.topology.class becomes spec.topology.classRef.name, and a spec.topology.rolloutAfter is reported rather than dropped.
  • org.openrewrite.kubernetes.clusterapi.MigrateMachineDeploymentToV1beta2
    • Migrate MachineDeployment to cluster.x-k8s.io/v1beta2
    • Rewrite a MachineDeployment into its v1beta2 form. spec.strategy splits into rollout.strategy, deletion.order and remediation, and spec.minReadySeconds moves onto the machines it creates. spec.progressDeadlineSeconds and spec.revisionHistoryLimit are gone, so a resource setting either is reported rather than silently losing them.
  • org.openrewrite.kubernetes.clusterapi.MigrateMachineDrainRuleToV1beta2
    • Migrate MachineDrainRule to cluster.x-k8s.io/v1beta2
    • Rewrite a MachineDrainRule into its v1beta2 form.
  • org.openrewrite.kubernetes.clusterapi.MigrateMachineHealthCheckToV1beta2
    • Migrate MachineHealthCheck to cluster.x-k8s.io/v1beta2
    • Rewrite a MachineHealthCheck into its v1beta2 form. Its checks and remediation are regrouped, and nodeStartupTimeout becomes checks.nodeStartupTimeoutSeconds rather than moving under deletion with the other durations.
  • org.openrewrite.kubernetes.clusterapi.MigrateMachinePoolToV1beta2
    • Migrate MachinePool to cluster.x-k8s.io/v1beta2
    • Rewrite a MachinePool into its v1beta2 form. spec.minReadySeconds moves onto the machines it creates, since MachinePoolSpec no longer holds it.
  • org.openrewrite.kubernetes.clusterapi.MigrateMachineSetToV1beta2
    • Migrate MachineSet to cluster.x-k8s.io/v1beta2
    • Rewrite a MachineSet into its v1beta2 form. spec.minReadySeconds moves onto the machines it creates, since MachineSetSpec no longer holds it.
  • org.openrewrite.kubernetes.clusterapi.MigrateMachineToV1beta2
    • Migrate Machine to cluster.x-k8s.io/v1beta2
    • Rewrite a Machine into its v1beta2 form. References name an API group rather than an apiVersion, and each metav1.Duration becomes whole seconds under deletion.
  • org.openrewrite.kubernetes.clusterapi.MigrateMetal3ProviderToV1beta2
    • Migrate Cluster API Provider Metal3 resources to v1beta2
    • Change the apiVersion of the resources served by Cluster API Provider Metal3 to v1beta2. Check first that the Metal3 release you run serves v1beta2 at all: as late as provider v1.10.1, api/v1beta1 is still the hub version and no v1beta2 package is shipped, and an apiVersion naming a version the CRD does not serve is rejected on apply. This recipe changes apiVersion only. Whatever else this provider reshaped in v1beta2 is defined by the provider rather than by the Cluster API contract, so review the resources it touches against the provider's own migration notes.
  • org.openrewrite.kubernetes.clusterapi.MigrateOpenStackProviderToV1beta2
    • Migrate Cluster API Provider OpenStack resources to v1beta2
    • Change the apiVersion of the OpenStackCluster, OpenStackClusterTemplate, OpenStackMachine and OpenStackMachineTemplate resources served by Cluster API Provider OpenStack to v1beta2. OpenStackServer, OpenStackClusterIdentity and OpenStackFloatingIPPool are still on v1alpha1 and are left alone. This recipe changes apiVersion only. Whatever else this provider reshaped in v1beta2 is defined by the provider rather than by the Cluster API contract, so review the resources it touches against the provider's own migration notes.
  • org.openrewrite.kubernetes.clusterapi.MigrateToClusterApiV1beta2
    • Migrate Cluster API resources to v1beta2
    • Migrate every custom resource Cluster API owns to v1beta2. v1beta1 has been deprecated since v1.11 and stops being served in v1.16. The cluster.x-k8s.io kinds move fields and apiVersion together; addons and ipam change apiVersion only, because those kinds are the same shape under a new name. Two things are deliberately left behind. The four Kubeadm* kinds are not migrated at all: extraArgs changes from a map to a list throughout the embedded kubeadm configuration and the control plane regroups half its spec, so a bare swap is either rejected outright or accepted while the apiserver prunes what moved. And infrastructure.cluster.x-k8s.io is out of scope, because that group belongs to the providers, each of which decides for itself what v1beta2 means. Both have to be migrated by hand.
  • org.openrewrite.kubernetes.crd.FindCustomResourcesUsingDeprecatedCrdFields
    • Find custom resources using deprecated CRD fields
    • Find custom resources that set a field which a CustomResourceDefinition in this repository marks deprecated, or that are on a version the CustomResourceDefinition deprecates. controller-gen copies Go doc comments verbatim into a CRD's OpenAPI schema description, so a field deprecated in Go ships its own deprecation notice inside the CRD and no per-CRD configuration is needed.
  • org.openrewrite.kubernetes.helm.ChangeChartVersion
    • Change Helm chart version
    • Propagate a Helm chart version across every file that restates it: the chart's own Chart.yaml, the dependencies of the charts that consume it, Flux HelmRelease resources, k0rdent ClusterTemplate, ProviderTemplate and ServiceTemplate resources, and optionally files whose name encodes the version. dependencies[].version is a range, so by default a range that the new version already satisfies is left alone rather than pinned. Chart.lock is never edited, because its digest cannot be recomputed here; it is reported instead. Files under a chart's templates directory are Go template text and are left alone. A k0rdent template's metadata.name also encodes the chart version, but a name is an identity that ClusterDeployment, Release and *TemplateChain resources point at. Renaming it here would leave those references dangling, so this recipe changes only version fields; org.openrewrite.kubernetes.k0rdent.ChangeTemplateVersion moves the name and everything that references it together.
  • org.openrewrite.kubernetes.k0rdent.ChangeTemplateVersion
    • Change k0rdent template version
    • Move a k0rdent ClusterTemplate, ProviderTemplate or ServiceTemplate to a new chart version, taking its name and everything that points at that name along with it. k0rdent encodes the chart version in the template's metadata.name, so a version bump renames the resource: aws-standalone-cp-1-0-42 becomes aws-standalone-cp-1-0-43. That name is referenced from ClusterDeployment.spec.template, from services[].template on a ClusterDeployment or MultiClusterService, from Release.spec.kcm.template, spec.regional.template, spec.capi.template and spec.providers[].template, from spec.core.kcm.template, spec.core.capi.template and spec.providers[].template on a Management or Region, and from the supportedTemplates of a ClusterTemplateChain or ServiceTemplateChain. All of them move together here, along with any file whose name encodes the template name, because a rename that misses one of them leaves a reference the controller cannot resolve. A template in a file that renders through a template engine is reported and left alone, and so are its referrers: its name is whatever the engine produces, so nothing can be moved without stranding the rest. This changes the template's own spec.helm.chartSpec.version too, but not the chart it points at. Run org.openrewrite.kubernetes.helm.ChangeChartVersion alongside it to move the chart's own Chart.yaml, the charts that depend on it, and any Flux HelmRelease.
  • org.openrewrite.kubernetes.k0rdent.MigrateDeprecatedServiceSpecFields
    • Migrate deprecated k0rdent serviceSpec fields
    • Move the fields k0rdent deprecated on spec.serviceSpec into the spec.serviceSpec.provider.config blob that supersedes them, on ClusterDeployment and MultiClusterService. The nine that move are syncMode, templateResourceRefs, policyRefs, driftIgnore, driftExclusions, priority, stopOnConflict, reload and continueOnError, plus createNamespace and replace on each service's helmOptions, which move into helmOptions.installOptions. reload is renamed to reloader on the way, because that is the key the state management provider unmarshals; a hand migration that keeps the old spelling produces a manifest the apiserver accepts and the controller ignores. Fields are left where they are, and reported in a data table, when the move would change what the resource does: the document renders through Helm, so what is written is not what is applied; provider.name or provider.config is already set, in which case the controller is already ignoring the deprecated fields and moving them would switch settings on; installOptions already declares a different value; or the resource is declared against k0rdent.mirantis.com/v1alpha1, whose schema has no provider field at all, so the apiserver would prune whatever was written there. The provider.name case is the subtle one. StateManagementProviderConfigFromServiceSpec folds the deprecated fields into a config blob only when neither provider.name nor provider.config is set; name it, and every deprecated field is discarded. Moving them into provider.config would hand a named provider a syncMode, priority or reloader it is not acting on today.
  • org.openrewrite.kubernetes.kustomize.UpdateImageTag
    • Update kustomize image
    • Update the newName, newTag or digest of an entry in a kustomization's images block, which is where kustomize edit set image and the sed, yq and Python scripts that stand in for it write an image pin. Only an entry that is already there is updated; an image the kustomization does not already override is left alone rather than added. A commented out entry stays a comment.
  • org.openrewrite.kubernetes.metallb.MetalLB
    • Migrate to current MetalLB Service configuration
    • Bring the Service side of a MetalLB installation up to date: annotations move off the deprecated metallb.universe.tf domain onto metallb.io, and an address pinned in the deprecated spec.loadBalancerIP moves into the metallb.io/loadBalancerIPs annotation that replaced it. These are MetalLB's own conventions rather than Kubernetes API migrations. Nothing here applies to a cluster whose LoadBalancer services are served by a cloud provider or by another bare metal load balancer, so scope the run to the manifests MetalLB serves. The domain rename runs first, so that a service already carrying metallb.universe.tf/loadBalancerIPs is compared against its migrated name.
  • org.openrewrite.kubernetes.metallb.MigrateLoadBalancerIpToMetalLbAnnotation
    • Migrate Service spec.loadBalancerIP to the MetalLB annotation
    • Move the address a type: LoadBalancer Service pins in spec.loadBalancerIP, deprecated in Kubernetes 1.24, into the metallb.io/loadBalancerIPs annotation MetalLB reads in its place. spec.loadBalancerIP holds a single address, so a dual stack service can name only one of its two families there and silently takes whatever MetalLB allocates for the other; the annotation takes a comma separated list and is the only way to pin both. MetalLB refuses to allocate at all for a service that sets both the annotation and spec.loadBalancerIP. Where the annotation is already present this therefore drops spec.loadBalancerIP when the two agree, and reports it when they disagree rather than picking an address on the author's behalf. This annotation means nothing to a cloud provider's load balancer controller, so run it only against manifests MetalLB serves.
  • org.openrewrite.kubernetes.metallb.MigrateMetalLbAnnotationPrefix
    • Migrate MetalLB annotations to the metallb.io domain
    • Rename the MetalLB Service annotations that moved from the metallb.universe.tf domain to metallb.io in MetalLB 0.14.9. The old domain still works, but the controller now raises a deprecatedAnnotation event against every service using it and the release notes reserve the right to drop the compatibility shim. Only the four annotations that genuinely moved are renamed — address-pool, loadBalancerIPs, allow-shared-ip and the controller-written ip-allocated-from-pool — so an unrelated metallb.universe.tf key keeps its domain. MetalLB prefers the metallb.io spelling wherever both are present, which makes the deprecated twin dead weight. Such a twin is dropped when it carries the same value and reported otherwise, rather than renamed into a duplicate key. This is MetalLB's own annotation domain, not a Kubernetes API migration; a cluster load balanced by anything else is unaffected.
  • org.openrewrite.kubernetes.migrate.MigrateHorizontalPodAutoscalerToV2
    • Migrate HorizontalPodAutoscaler to autoscaling/v2
    • Move HorizontalPodAutoscaler off the autoscaling beta APIs — v2beta1, removed in Kubernetes v1.25, and v2beta2, removed in v1.26 — onto autoscaling/v2, restructuring the metric targets v2beta1 wrote inline. v2beta2 is autoscaling/v2 under another name, so those resources only change version. A v2beta1 resource is rewritten the way the apiserver itself converted it: targetAverageUtilization becomes target.averageUtilization under target.type: Utilization and targetAverageValue becomes target.averageValue under target.type: AverageValue; metricName and its selector become the metric identifier; and for an object metric the target naming the described object becomes describedObject, freeing target for the metric target built from targetValue and averageValue. A metric that sets a combination autoscaling/v2 validation rejects — a resource metric targeting both a utilization and a raw value, or an external metric targeting both a total and a per-pod value — is left on its old API version and marked with the reason.
  • org.openrewrite.kubernetes.migrate.MigrateIngressToNetworkingV1
    • Migrate Ingress to networking.k8s.io/v1
    • Move Ingress from extensions/v1beta1 and networking.k8s.io/v1beta1, both removed in Kubernetes v1.22, to networking.k8s.io/v1, restructuring the body the new version requires. spec.backend becomes spec.defaultBackend, every backend.serviceName and backend.servicePort pair becomes backend.service.name and backend.service.port, and every path gains the explicit pathType: ImplementationSpecific that v1beta1 used to default to. servicePort is an int-or-string, so how it is written decides where it lands: an unquoted 8080 is the port number and becomes port.number, while a quoted &quot;8080&quot; or a bare http is the port's name and becomes port.name. An Ingress the restructuring cannot carry over in full is left on its old API version and marked with the reason, rather than being handed to the apiserver in a shape it rejects.
  • org.openrewrite.kubernetes.migrate.MigratePodDisruptionBudgetToV1
    • Migrate PodDisruptionBudget to policy/v1
    • Move PodDisruptionBudget from policy/v1beta1, removed in Kubernetes 1.25, to policy/v1, adjusting an empty spec.selector so the budget goes on covering the same pods. Under policy/v1beta1 an empty selector (\{\}) selected no pods; under policy/v1 it selects every pod in the namespace, so changing only the API version would silently turn a budget that did nothing into one that blocks every eviction in its namespace. An unset selector means "no pods" in both versions, so the empty selector is dropped rather than carried over.
  • org.openrewrite.kubernetes.migrate.MigrateToAPIv1_16
    • Migrate to Kubernetes API v1.16
    • This recipe will apply changes commonly needed when migrating to Kubernetes API v1.16.
  • org.openrewrite.kubernetes.migrate.MigrateToAPIv1_17
    • Migrate to Kubernetes API v1.17
    • This recipe will apply changes commonly needed when migrating to Kubernetes API v1.17. Kubernetes v1.17 removed no API version, so this is an alias for the v1.16 migration.
  • org.openrewrite.kubernetes.migrate.MigrateToAPIv1_18
    • Migrate to Kubernetes API v1.18
    • This recipe will apply changes commonly needed when migrating to Kubernetes API v1.18. Kubernetes v1.18 removed no API version, so this is an alias for the v1.16 migration.
  • org.openrewrite.kubernetes.migrate.MigrateToAPIv1_19
    • Migrate to Kubernetes API v1.19
    • This recipe will apply changes commonly needed when migrating to Kubernetes API v1.19. Kubernetes v1.19 removed no API version, so this is an alias for the v1.16 migration.
  • org.openrewrite.kubernetes.migrate.MigrateToAPIv1_20
    • Migrate to Kubernetes API v1.20
    • This recipe will apply changes commonly needed when migrating to Kubernetes API v1.20. Kubernetes v1.20 removed no API version, so this is an alias for the v1.16 migration.
  • org.openrewrite.kubernetes.migrate.MigrateToAPIv1_21
    • Migrate to Kubernetes API v1.21
    • This recipe will apply changes commonly needed when migrating to Kubernetes API v1.21. Kubernetes v1.21 removed no API version, so this is an alias for the v1.16 migration.
  • org.openrewrite.kubernetes.migrate.MigrateToAPIv1_22
    • Migrate to Kubernetes API v1.22
    • This recipe will apply changes commonly needed when migrating to Kubernetes API v1.22.
  • org.openrewrite.kubernetes.migrate.MigrateToAPIv1_23
    • Migrate to Kubernetes API v1.23
    • This recipe will apply changes commonly needed when migrating to Kubernetes API v1.23. Kubernetes v1.23 removed no API version, so this is an alias for the v1.22 migration.
  • org.openrewrite.kubernetes.migrate.MigrateToAPIv1_24
    • Migrate to Kubernetes API v1.24
    • This recipe will apply changes commonly needed when migrating to Kubernetes API v1.24. Kubernetes v1.24 removed no API version, so this is an alias for the v1.22 migration.
  • org.openrewrite.kubernetes.migrate.MigrateToAPIv1_25
    • Migrate to Kubernetes API v1.25
    • This recipe will apply changes commonly needed when migrating to Kubernetes API v1.25.
  • org.openrewrite.kubernetes.migrate.MigrateToAPIv1_26
    • Migrate to Kubernetes API v1.26
    • This recipe will apply changes commonly needed when migrating to Kubernetes API v1.26.
  • org.openrewrite.kubernetes.migrate.MigrateToAPIv1_27
    • Migrate to Kubernetes API v1.27
    • This recipe will apply changes commonly needed when migrating to Kubernetes API v1.27.
  • org.openrewrite.kubernetes.migrate.MigrateToAPIv1_28
    • Migrate to Kubernetes API v1.28
    • This recipe will apply changes commonly needed when migrating to Kubernetes API v1.28. Kubernetes v1.28 removed no API version, so this is an alias for the v1.27 migration.
  • org.openrewrite.kubernetes.migrate.MigrateToAPIv1_29
    • Migrate to Kubernetes API v1.29
    • This recipe will apply changes commonly needed when migrating to Kubernetes API v1.29.
  • org.openrewrite.kubernetes.migrate.MigrateToAPIv1_30
    • Migrate to Kubernetes API v1.30
    • This recipe will apply changes commonly needed when migrating to Kubernetes API v1.30. Kubernetes v1.30 removed no API version, so this is an alias for the v1.29 migration.
  • org.openrewrite.kubernetes.migrate.MigrateToAPIv1_31
    • Migrate to Kubernetes API v1.31
    • This recipe will apply changes commonly needed when migrating to Kubernetes API v1.31. Kubernetes v1.31 removed no API version, so this is an alias for the v1.29 migration.
  • org.openrewrite.kubernetes.migrate.MigrateToAPIv1_32
    • Migrate to Kubernetes API v1.32
    • This recipe will apply changes commonly needed when migrating to Kubernetes API v1.32.
  • org.openrewrite.kubernetes.migrate.MigrateToAPIv1_33
    • Migrate to Kubernetes API v1.33
    • This recipe will apply changes commonly needed when migrating to Kubernetes API v1.33.
  • org.openrewrite.kubernetes.migrate.MigrateToAPIv1_34
    • Migrate to Kubernetes API v1.34
    • This recipe will apply changes commonly needed when migrating to Kubernetes API v1.34.
  • org.openrewrite.kubernetes.migrate.MigrateToAPIv1_35
    • Migrate to Kubernetes API v1.35
    • This recipe will apply changes commonly needed when migrating to Kubernetes API v1.35.
  • org.openrewrite.kubernetes.migrate.MigrateToAPIv1_36
    • Migrate to Kubernetes API v1.36
    • This recipe will apply changes commonly needed when migrating to Kubernetes API v1.36. Kubernetes v1.36 removed no API version, so this is an alias for the v1.35 migration.
  • org.openrewrite.kubernetes.rbac.AddRuleToRole
    • Add RBAC rules
    • Add RBAC rules to ClusterRoles or namespaced Roles.
  • org.openrewrite.kubernetes.resource.CapResourceValueToMaximum
    • Cap exceeds resource value
    • Cap resource values that exceed a specific maximum.
  • org.openrewrite.kubernetes.resource.FindExceedsResourceRatio
    • Find exceeds resource ratio
    • Find resource manifests that have requests to limits ratios beyond a specific maximum.
  • org.openrewrite.kubernetes.resource.FindExceedsResourceValue
    • Find exceeds resource limit
    • Find resource manifests that have limits set beyond a specific maximum.
  • org.openrewrite.kubernetes.search.FindAdmissionWebhookV1beta1
    • Find admissionregistration.k8s.io/v1beta1 webhook configurations
    • Find MutatingWebhookConfiguration and ValidatingWebhookConfiguration resources still on the admissionregistration.k8s.io/v1beta1 API removed in Kubernetes v1.22. Moving to admissionregistration.k8s.io/v1 is not a version swap: every webhook must declare admissionReviewVersions and sideEffects, both of which have no default in v1, and the v1beta1 defaults of failurePolicy: Ignore, matchPolicy: Exact and timeoutSeconds: 30 change to Fail, Equivalent and 10.
  • org.openrewrite.kubernetes.search.FindAnnotation
    • Find annotation
    • Find annotations that optionally match a given regex.
  • org.openrewrite.kubernetes.search.FindContainerMissingConfiguration
    • Find containers with missing configuration
    • Find containers of a Kubernetes workload that are missing a given piece of configuration. Every container is evaluated on its own, so a sidecar that omits the configuration is reported even when the application container next to it sets it.
  • org.openrewrite.kubernetes.search.FindContainerResourceCoverage
    • Find container resource coverage
    • Profile the compute resources and probes every container of every workload declares. Quantities are reported both as written and normalized to millicores and bytes, and each row carries the quality of service class the kubelet would give the pod the container belongs to.
  • org.openrewrite.kubernetes.search.FindCustomResourceDefinitionV1beta1
    • Find apiextensions.k8s.io/v1beta1 CustomResourceDefinitions
    • Find CustomResourceDefinition resources still on the apiextensions.k8s.io/v1beta1 API removed in Kubernetes v1.22. Moving to apiextensions.k8s.io/v1 is not a version swap: spec.validation, spec.subresources and spec.additionalPrinterColumns move under each entry of spec.versions, spec.version is dropped in favour of spec.versions, a structural schema and an explicit spec.preserveUnknownFields: false become mandatory, and spec.conversion.webhookClientConfig moves to spec.conversion.webhook.clientConfig alongside a required spec.conversion.webhook.conversionReviewVersions.
  • org.openrewrite.kubernetes.search.FindDanglingResourceReferences
    • Find dangling Kubernetes resource references
    • Find resources that refer by name to a ConfigMap, Secret, ServiceAccount, Service, PersistentVolumeClaim, Role, ClusterRole, PriorityClass or scale target that this repository declares nowhere. There is no safe automated fix for a dangling reference — the name is either a typo, a leftover, or satisfied out of band — so this only reports. Namespace is ignored when resolving, a kustomization's namePrefix and nameSuffix are replayed so that the name a cluster sees resolves as well as the one on disk, and references whose value is templated, whose target kind appears nowhere in the repository, or whose target kind has a name some template computes are all left alone.
  • org.openrewrite.kubernetes.search.FindDisallowedImageTags
    • Find disallowed image tags
    • The set of image tags to find which are considered disallowed.
  • org.openrewrite.kubernetes.search.FindHarcodedIPAddresses
    • Find hardcoded IP addresses
    • Find hardcoded IP address anywhere in text-based files.
  • org.openrewrite.kubernetes.search.FindHorizontalPodAutoscalerV2beta
    • Find autoscaling/v2beta1 and autoscaling/v2beta2 HorizontalPodAutoscalers
    • Find HorizontalPodAutoscaler resources still on an autoscaling beta API; v2beta1 was removed in Kubernetes v1.25 and v2beta2 in v1.26. Moving to autoscaling/v2 is not a version swap: each entry of spec.metrics carries a target object, so targetAverageUtilization becomes target.averageUtilization with target.type: Utilization and targetAverageValue becomes target.averageValue with target.type: AverageValue.
  • org.openrewrite.kubernetes.search.FindImage
    • Find image by name
    • The image name to search for in containers and initContainers.
  • org.openrewrite.kubernetes.search.FindIngressV1beta1
    • Find networking.k8s.io/v1beta1 Ingresses
    • Find Ingress resources still on the networking.k8s.io/v1beta1 API removed in Kubernetes v1.22. Moving to networking.k8s.io/v1 is not a version swap: backend.serviceName and backend.servicePort become backend.service.name and backend.service.port, spec.backend becomes spec.defaultBackend, and every path needs an explicit pathType.
  • org.openrewrite.kubernetes.search.FindKubernetesResources
    • Find Kubernetes resources
    • An inventory of every Kubernetes resource in a repository, one row per YAML document. The pod spec path column reports where each kind keeps its containers, so the workloads this module cannot reach are counted rather than quietly skipped.
  • org.openrewrite.kubernetes.search.FindKustomizeImages
    • Find kustomize images
    • An inventory of every image a kustomization overrides. The images block is where a repository's image pins actually live once kustomize is in play, and it is rewritten by kustomize edit set image, sed, yq and hand edits alike, so it is worth knowing where they all are.
  • org.openrewrite.kubernetes.search.FindManifestFlavors
    • Find Kubernetes manifest flavors
    • Classify every YAML file in a repository by what it actually is — a manifest, a Helm chart template, a kustomization, something else entirely — and by whether an edit to it would mean what it appears to mean. This is the denominator every other Kubernetes report is a fraction of.
  • org.openrewrite.kubernetes.search.FindMissingDigest
    • Find missing image digest
    • Find instances of a container name that fails to specify a digest.
  • org.openrewrite.kubernetes.search.FindMissingOrInvalidAnnotation
    • Find annotation
    • Find annotations that optionally match a given value.
  • org.openrewrite.kubernetes.search.FindMissingOrInvalidLabel
    • Find label
    • Find labels that optionally match a given regex.
  • org.openrewrite.kubernetes.search.FindNonTlsIngress
    • Find non-TLS Ingresses
    • Find Ingress resources that don't disallow HTTP or don't have TLS configured.
  • org.openrewrite.kubernetes.search.FindPodDisruptionBudgetsSelectingAllPods
    • Find PodDisruptionBudget resources selecting every pod
    • Find policy/v1 PodDisruptionBudget resources whose spec.selector is empty (\{\}), which selects every pod in the namespace and so can block all evictions in it — stalling node drains and cluster upgrades. This is occasionally deliberate, but it is also what a naive version bump from policy/v1beta1 produces, because there the same empty selector selected no pods at all.
  • org.openrewrite.kubernetes.search.FindResourceMissingConfiguration
    • Find missing configuration
    • Find Kubernetes resources with missing configuration.
  • org.openrewrite.kubernetes.services.FindServiceExternalIPs
    • Find uses of externalIP
    • Find any Service whose externalIP list contains, or does not contain, one of a list of IPs.
  • org.openrewrite.kubernetes.services.FindServicesByType
    • Service type
    • Type of Kubernetes Service to find.
  • org.openrewrite.kubernetes.services.UpdateServiceExternalIP
    • Update Service externalIP
    • Swap out an IP address with another one in Service externalIP settings.

rewrite-liberty​

License: Apache License Version 2.0

13 recipes

rewrite-logging-frameworks​

License: Moderne Source Available License

130 recipes

rewrite-micrometer​

License: Moderne Source Available License

7 recipes

rewrite-micronaut​

License: Apache License Version 2.0

40 recipes

rewrite-migrate-java​

License: Moderne Source Available License

505 recipes

rewrite-migrate-kotlin​

License: Moderne Proprietary License

34 recipes

  • androidx.compose.animation.ReplaceDeprecatedAnimationCore1Methods
    • Replace deprecated animation-core methods
    • Automatically generated recipes to replace deprecated Kotlin methods based on @Deprecated(replaceWith=ReplaceWith(...)) annotations.
  • androidx.compose.material.ReplaceDeprecatedMaterial1Methods
    • Replace deprecated material methods
    • Automatically generated recipes to replace deprecated Kotlin methods based on @Deprecated(replaceWith=ReplaceWith(...)) annotations.
  • androidx.compose.material3.ReplaceDeprecatedMaterial31Methods
    • Replace deprecated material3 methods
    • Automatically generated recipes to replace deprecated Kotlin methods based on @Deprecated(replaceWith=ReplaceWith(...)) annotations.
  • androidx.compose.runtime.ReplaceDeprecatedRuntime1Methods
    • Replace deprecated runtime methods
    • Automatically generated recipes to replace deprecated Kotlin methods based on @Deprecated(replaceWith=ReplaceWith(...)) annotations.
  • org.jetbrains.kotlinx.ReplaceDeprecatedKotlinxCollectionsImmutable0Methods
    • Replace deprecated kotlinx-collections-immutable methods
    • Automatically generated recipes to replace deprecated Kotlin methods based on @Deprecated(replaceWith=ReplaceWith(...)) annotations.
  • org.jetbrains.kotlinx.ReplaceDeprecatedKotlinxCoroutinesCore1Methods
    • Replace deprecated kotlinx-coroutines-core methods
    • Automatically generated recipes to replace deprecated Kotlin methods based on @Deprecated(replaceWith=ReplaceWith(...)) annotations.
  • org.jetbrains.kotlinx.ReplaceDeprecatedKotlinxDatetime0Methods
    • Replace deprecated kotlinx-datetime methods
    • Automatically generated recipes to replace deprecated Kotlin methods based on @Deprecated(replaceWith=ReplaceWith(...)) annotations.
  • org.jetbrains.kotlinx.ReplaceDeprecatedKotlinxIoCore0Methods
    • Replace deprecated kotlinx-io-core methods
    • Automatically generated recipes to replace deprecated Kotlin methods based on @Deprecated(replaceWith=ReplaceWith(...)) annotations.
  • org.jetbrains.kotlinx.ReplaceDeprecatedKotlinxSerializationCore1Methods
    • Replace deprecated kotlinx-serialization-core methods
    • Automatically generated recipes to replace deprecated Kotlin methods based on @Deprecated(replaceWith=ReplaceWith(...)) annotations.
  • org.openrewrite.kotlin.compose.ReplaceDeprecatedComposeMethods
    • Replace deprecated Jetpack Compose methods
    • Replace deprecated Jetpack Compose method calls with their recommended replacements, based on @Deprecated(replaceWith=ReplaceWith(...)) annotations.
  • org.openrewrite.kotlin.exposed.ExposedChangeMethodNames
    • Rename Exposed deprecated methods for 1.0
    • Rename deprecated Exposed method and property references to their 1.0 replacements.
  • org.openrewrite.kotlin.exposed.ExposedChangeTypes
    • Migrate Exposed type references to 1.0 packages
    • Change fully qualified type references from Exposed 0.x packages to Exposed 1.0 packages. The 1.0 release reorganized all packages under org.jetbrains.exposed.v1.* and split classes across core, jdbc, and dao modules.
  • org.openrewrite.kotlin.exposed.ExposedUpgradeGradleDependencies
    • Upgrade Exposed Gradle dependencies to 1.0
    • Update JetBrains Exposed Gradle dependencies for the 1.0.0 migration. Upgrades dependency versions and handles the exposed-migration module split.
  • org.openrewrite.kotlin.exposed.UpgradeToExposed_1
    • Migrate to JetBrains Exposed 1.0
    • Migrate from JetBrains Exposed 0.x to 1.0.0. This includes package reorganization (adding v1 prefix), type moves between modules, class renames, method renames, and Gradle dependency updates. Some changes require manual intervention and are not covered by this recipe: Table.uuid() should be changed to Table.javaUUID() for java.util.UUID values, DateColumnType with constructor parameter time=false or time=true should be split into JodaLocalDateColumnType or JodaLocalDateTimeColumnType, SqlExpressionBuilder.* usages should be replaced with top-level function imports, and Statement.execute() calls should use BlockingExecutable wrapping.
  • org.openrewrite.kotlin.kotlinx.ReplaceDeprecatedKotlinxMethods
    • Replace deprecated kotlinx methods
    • Replace deprecated Kotlin extension library method calls with their recommended replacements, based on @Deprecated(replaceWith=ReplaceWith(...)) annotations.
  • org.openrewrite.kotlin.migrate.RemoveDeprecatedKotlinGradleProperties
    • Remove deprecated Kotlin Gradle properties
    • Remove deprecated Kotlin Gradle properties from gradle.properties. kotlin.experimental.coroutines was removed in Kotlin 2.x.
  • org.openrewrite.kotlin.migrate.RemoveRedundantKotlinStdlib
    • Remove redundant kotlin-stdlib dependencies
    • Remove explicit kotlin-stdlib, kotlin-stdlib-jdk7, kotlin-stdlib-jdk8, and kotlin-stdlib-common dependencies. The Kotlin Gradle plugin has automatically included the stdlib since Kotlin 1.4, making explicit declarations redundant.
  • org.openrewrite.kotlin.migrate.RenameKotlinOptionsToCompilerOptions
    • Rename the kotlinOptions block to compilerOptions
    • Rename the deprecated kotlinOptions DSL block to compilerOptions in Gradle build files (Groovy and Kotlin DSL). The kotlinOptions DSL was deprecated in Kotlin 2.0 and removed in Kotlin 2.2. Note: in the Kotlin DSL the assignments inside the block must also be modernized for the result to compile; see UseJvmTargetProviderSyntax and UseFreeCompilerArgsAddAll.
  • org.openrewrite.kotlin.migrate.ReplaceDeprecatedAppendln
    • Replace deprecated appendln with appendLine
    • Replace appendln() with appendLine(). This was deprecated in Kotlin 1.4 and becomes an error in Kotlin 2.1.
  • org.openrewrite.kotlin.migrate.ReplaceDeprecatedCapitalizeAndDecapitalize
    • Replace deprecated capitalize and decapitalize
    • Replace String.capitalize() with String.replaceFirstChar \{ if (it.isLowerCase()) it.titlecase() else it.toString() \} and String.decapitalize() with String.replaceFirstChar \{ it.lowercase() \}. These were deprecated in Kotlin 1.5 and become errors in Kotlin 2.1.
  • org.openrewrite.kotlin.migrate.ReplaceDeprecatedCharCaseConversions
    • Replace deprecated Char case conversions
    • Replace Char.toLowerCase() with Char.lowercaseChar() and Char.toUpperCase() with Char.uppercaseChar(). These were deprecated in Kotlin 1.5 and become errors in Kotlin 2.1.
  • org.openrewrite.kotlin.migrate.ReplaceDeprecatedStringCaseConversions
    • Replace deprecated String case conversions
    • Replace String.toLowerCase() with String.lowercase() and String.toUpperCase() with String.uppercase(). These were deprecated in Kotlin 1.5 and become errors in Kotlin 2.1.
  • org.openrewrite.kotlin.migrate.ReplaceEnumValuesFunctionWithEnumEntries
    • Replace enumValues&lt;T&gt;() with enumEntries&lt;T&gt;()
    • Replace calls to enumValues&lt;T&gt;() with enumEntries&lt;T&gt;(). The enumEntries function returns an efficient immutable list instead of creating a new array. Deprecated since Kotlin 1.9, recommended replacement for Kotlin 2.x.
  • org.openrewrite.kotlin.migrate.ReplaceEnumValuesWithEntries
    • Replace Enum.values() with Enum.entries
    • Replace calls to Enum.values() with the Enum.entries property. The entries property returns an efficient immutable list instead of creating a new array on each call. Deprecated since Kotlin 1.9, recommended replacement for Kotlin 2.x.
  • org.openrewrite.kotlin.migrate.ReplaceKotlinOptionsWithCompilerOptions
    • Replace kotlinOptions with compilerOptions in Gradle build files
    • Migrate the deprecated kotlinOptions DSL block to compilerOptions in Gradle build files (Groovy and Kotlin DSL). Renames the block and, in the Kotlin DSL, modernizes the assignments inside it to the Provider-style setters (jvmTarget.set(JvmTarget.JVM_X), freeCompilerArgs.addAll(...)) so the result compiles against the compilerOptions DSL. The kotlinOptions DSL was deprecated in Kotlin 2.0 and removed in Kotlin 2.2.
  • org.openrewrite.kotlin.migrate.UpgradeKotlinGradlePlugins
    • Upgrade Kotlin Gradle plugins to 2.x
    • Upgrade all org.jetbrains.kotlin.* Gradle plugins to Kotlin 2.x. This includes the core kotlin-jvm plugin as well as all official Kotlin Gradle plugins such as serialization, Spring, allopen, noarg, JPA, and parcelize.
  • org.openrewrite.kotlin.migrate.UpgradeKotlinxCoroutines_1_10
    • Upgrade to kotlinx-coroutines 1.10
    • Upgrade kotlinx-coroutines to 1.10.x and replace deprecated method calls.
  • org.openrewrite.kotlin.migrate.UpgradeKotlinxDatetime_0_7
    • Migrate to kotlinx-datetime 0.7
    • Migrate from kotlinx-datetime 0.6.x to 0.7.x. This includes replacing kotlinx.datetime.Instant and kotlinx.datetime.Clock with their kotlin.time equivalents and replacing deprecated method calls.
  • org.openrewrite.kotlin.migrate.UpgradeKotlinxSerialization_1_8
    • Upgrade to kotlinx-serialization 1.8
    • Upgrade kotlinx-serialization to 1.8.x and replace deprecated method calls.
  • org.openrewrite.kotlin.migrate.UpgradeToKotlin2
    • Migrate to Kotlin 2
    • Migrate deprecated Kotlin 1.x APIs to their Kotlin 2.x replacements and update Gradle build files for Kotlin 2.x compatibility. Deprecated APIs were deprecated in Kotlin 1.4-1.5 and become errors in Kotlin 2.1.
  • org.openrewrite.kotlin.migrate.UseFreeCompilerArgsAddAll
    • Use freeCompilerArgs.addAll(...) in Kotlin compilerOptions
    • In Gradle Kotlin DSL build scripts, replace the legacy freeCompilerArgs = listOf(...) assignment inside a compilerOptions (or kotlinOptions) block with the modern freeCompilerArgs.addAll(...), the idiomatic way to contribute arguments to the ListProperty.
  • org.openrewrite.kotlin.migrate.UseJvmTargetProviderSyntax
    • Use the jvmTarget provider syntax in Kotlin compilerOptions
    • In Gradle Kotlin DSL build scripts, replace the legacy jvmTarget = &quot;X&quot; string assignment inside a compilerOptions (or kotlinOptions) block with the modern Provider-style jvmTarget.set(JvmTarget.JVM_X), adding the JvmTarget import. The string-assignment form does not compile against the compilerOptions DSL, where jvmTarget is a Property&lt;JvmTarget&gt;.
  • org.openrewrite.kotlin.migrate.autovalue.AutoValueToDataClass
    • Migrate @AutoValue classes to Kotlin data classes
    • Replaces a Java or Kotlin @AutoValue abstract class with a Kotlin data class and rewrites its Kotlin and Java callers: x() accessors become x property reads (getX() in Java) and the static or companion create(..) factory becomes the constructor. A Java class becomes a .kt file in place of the .java file. Only classes consisting of abstract accessors and a single forwarding factory are converted; every @AutoValue class is listed in the AutoValueClasses data table with the reason it was skipped.
  • org.openrewrite.kotlin.replace.ReplaceKotlinMethod
    • Replace Kotlin method
    • Replaces Kotlin method calls based on @Deprecated(replaceWith=ReplaceWith(...)) annotations.

rewrite-migrate-python​

License: Moderne Proprietary License

161 recipes

  • org.openrewrite.python.cleanup.MergeNestedWithStatements
    • Merge nested with statements into one
    • Combine directly nested with statements into a single with when the outer body contains only the inner with. An async with is left alone, as is a comment between the two, an outer with holding other statements, and a pair whose context managers the merge would leave split across lines outside parentheses.
  • org.openrewrite.python.cleanup.MergeStartswithEndswith
    • Merge multiple startswith()/endswith() calls into one
    • When several startswith() or endswith() calls on the same receiver are joined by or, combine them into a single call with a tuple argument. It only fires where the receiver's type resolves to str or bytes, the receiver is a name or attribute, every argument is a string literal of the receiver's kind, and no comment would be lost.
  • org.openrewrite.python.cleanup.RemoveTrailingReturnNone
    • Remove trailing return None from functions
    • Delete return None or a bare return when it is the last statement in a function body and no other return yields a non-None value. A return holding a comment is kept, as is one that is the function's only statement.
  • org.openrewrite.python.cleanup.RemoveUnnecessaryAssign
    • Remove unnecessary assignment before return
    • Return the value directly where a variable is assigned and then immediately returned. A name that appears anywhere else in the function, a yield value, and a comment before the return are left alone.
  • org.openrewrite.python.cleanup.RemoveUselessObjectInheritance
    • Remove useless object inheritance
    • Remove redundant object base class from class declarations. In Python 3, all classes implicitly inherit from object. It only fires where the base's type resolves to the builtin object, and leaves alone a base list holding comments.
  • org.openrewrite.python.cleanup.ReplaceGetAttrWithConstant
    • Replace getattr(x, 'attr') with x.attr
    • Replace getattr(x, &quot;attr&quot;) calls with x.attr when the attribute name is a constant string that is a valid Python identifier. It leaves alone a shadowed getattr, a non-ASCII or name-mangled name, an object that would need parentheses, and a call holding comments.
  • org.openrewrite.python.cleanup.ReplaceLoggerWarn
    • Replace logger.warn() with logger.warning()
    • Replace warn() calls on a logging.Logger or logging.LoggerAdapter with warning(). The warn() method is a deprecated alias that should not be used. It only fires where the receiver's type resolves, and leaves alone the module-level logging.warn() and a subclass that overrides warn().
  • org.openrewrite.python.cleanup.ReplaceNotInTest
    • Replace not x in y with x not in y
    • Replace not x in y with x not in y. The not in operator is clearer than negating an in test. A chained comparison such as not a in b in c is left alone.
  • org.openrewrite.python.cleanup.ReplaceNotIsTest
    • Use is not instead of not ... is
    • Replace not x is y with x is not y. The is not operator is clearer than negating an is test. A chained comparison such as not a is b is c is left alone.
  • org.openrewrite.python.cleanup.ReplaceSetAttrWithConstant
    • Replace setattr() with constant attribute assignment
    • Replace a setattr(x, &quot;attr&quot;, value) statement with x.attr = value when the attribute name is a constant valid Python identifier. It leaves alone a shadowed setattr, a non-ASCII or name-mangled name, a call used as an expression, a call holding comments, and an object or value that may have side effects, since the assignment evaluates the value first.
  • org.openrewrite.python.cleanup.ReplaceYodaConditions
    • Replace Yoda conditions with normal comparisons
    • Replace Yoda conditions (e.g. None == x) with the conventional comparison order (e.g. x == None). A chained comparison, or one with a constant on both sides, is left alone. See Ruff rule SIM300.
  • org.openrewrite.python.cleanup.SimplifyBooleanReturn
    • Collapse if/else returning boolean literals
    • Replace if cond: return True / else: return False with return cond and the inverse with return not cond, including the fallthrough variant without an explicit else. A condition other than a comparison, a not, or an and/or of those is returned as bool(cond). The rewrite is declined where bool is not the builtin or the removed statements hold comments.
  • org.openrewrite.python.cleanup.UseItemsForKeyValueIteration
    • Replace zip(d.keys(), d.values()) with d.items()
    • When both .keys() and .values() are zipped together, replace with .items() which yields key-value pairs directly. Only a zip that a for-loop or comprehension iterates directly is replaced, and only where the receiver is a name or attribute read whose type resolves to dict.
  • org.openrewrite.python.cleanup.UseListClear
    • Replace del x[:] with x.clear()
    • Use .clear() instead of del x[:] to empty a list. The method call is more explicit and idiomatic. Only a receiver whose type resolves to list or bytearray is rewritten, since del x[:] raises on a dict or deque that .clear() would empty.
  • org.openrewrite.python.codequality.AllBranchesIdentical
    • Remove conditional with identical branches
    • Replace if/elif/else chains where every branch has the same body with just the body, since the condition has no effect on what code executes. A chain whose conditions may have side effects, such as a call, is left alone.
  • org.openrewrite.python.codequality.BooleanChecksNotInverted
    • Boolean checks should not be inverted
    • Replace inverted boolean comparisons like not (a == b) with the equivalent direct operator (a != b), and remove double negations like not (not x). An ordering such as not (a &lt; b) is only inverted where both operands' types resolve to integers, a chained comparison is left alone, as is a comparison inside a method such as __ne__ that the inverted operator would call. A double negation is only removed where its value is read as a truth value, as in a condition.
  • org.openrewrite.python.codequality.CodeQuality
    • Code quality
    • Apply all Python code quality recipes that change code: simplify boolean expressions, merge and collapse if chains, and remove dead conditions and writes. Search-only recipes, which mark code for review, are not included.
  • org.openrewrite.python.codequality.CollapsibleIfStatements
    • Merge collapsible if statements
    • Combine nested if statements that have no else branch into a single if joined with and.
  • org.openrewrite.python.codequality.FindSuspiciousChainedComparison
    • Find suspicious chained comparisons
    • Find chained comparisons that mix &lt;/&lt;= with &gt;/&gt;= (for example 0 &lt;= x &gt;= 10), where the links point in opposite directions and the chain is almost always a mistake.
  • org.openrewrite.python.codequality.MergeIdenticalBranches
    • Merge consecutive branches with identical bodies
    • Combine consecutive if/elif branches that have the same body into a single branch with conditions joined by or.
  • org.openrewrite.python.codequality.RemoveDuplicateConditions
    • Remove duplicate conditions in if/elif chains
    • Remove elif branches whose condition is identical to an earlier branch in the same if/elif chain, since the duplicate branch is dead code that can never execute. A condition that may have side effects, such as a call, is kept, since evaluating it again can give a different result.
  • org.openrewrite.python.codequality.RemoveSelfAssignment
    • Remove self-assignments
    • Remove statements inside a function that assign a plain local name to itself (x = x), since they have no effect. Class-body and module-level X = X bind a new name from an enclosing one and are left alone, as are attribute and subscript targets, which run __set__ and __setitem__.
  • org.openrewrite.python.codequality.RemoveUnconditionalValueOverwrite
    • Remove unconditional value overwrites
    • Remove a constant written to a dict key when the next statement overwrites the same key. Only a dict the enclosing function built with \{...\} or dict() and has not yet passed on qualifies, and only for constant keys outside try and with blocks. Writes to attributes, parameters and globals are left alone, because another thread, an alias or a setter can observe them.
  • org.openrewrite.python.codequality.SimplifyBooleanLiteral
    • Simplify boolean literal comparisons
    • Replace x != True and x is not True with not x, and x == True and x is True with x where only the truth of the result is read. Only fires where x's type resolves to bool. A comparison against False is left alone, because x may be None where its type reads as bool, and None and False compare differently.
  • org.openrewrite.python.codequality.SimplifyRedundantLogicalExpression
    • Simplify redundant logical expressions
    • Replace x and x with x and x or x with x. Identical operands in a logical expression are redundant and often indicate a copy-paste mistake.
  • org.openrewrite.python.migrate.DependencyInsight
    • Python dependency insight
    • Find Python dependencies, including transitive dependencies, matching a package name pattern. Results include the resolved version, scope, and whether the dependency is direct or transitive.
  • org.openrewrite.python.migrate.FindAifcModule
    • Find deprecated aifc module usage
    • The aifc module was deprecated in Python 3.11 and removed in Python 3.13. Use third-party audio libraries instead.
  • org.openrewrite.python.migrate.FindAsyncioCoroutineDecorator
    • Find deprecated @asyncio.coroutine decorator
    • Find usage of the deprecated @asyncio.coroutine decorator which was removed in Python 3.11. Convert to async def syntax with await instead of yield from.
  • org.openrewrite.python.migrate.FindAudioopModule
    • Find deprecated audioop module usage
    • The audioop module was deprecated in Python 3.11 and removed in Python 3.13. Use pydub, numpy, or scipy for audio operations.
  • org.openrewrite.python.migrate.FindBackoffDecoratorsNotMigrated
    • Find backoff decorators that need a hand migration
    • Mark every @backoff.on_exception and @backoff.on_predicate that org.openrewrite.python.migrate.ReplaceBackoffDecoratorsWithTenacity declines to rewrite, with the reason, and record it in a data table. This changes no behaviour; it scopes the hand migration left after the mechanical one. The markup it prints is not valid Python, so run it for a report rather than as part of a migration.
  • org.openrewrite.python.migrate.FindCgiModule
    • Find deprecated cgi module usage
    • The cgi module was deprecated in Python 3.11 and removed in Python 3.13. Use urllib.parse for query string parsing, html.escape() for escaping, and web frameworks or email.message for form handling.
  • org.openrewrite.python.migrate.FindCgitbModule
    • Find deprecated cgitb module usage
    • The cgitb module was deprecated in Python 3.11 and removed in Python 3.13. Use the standard logging and traceback modules for error handling.
  • org.openrewrite.python.migrate.FindChunkModule
    • Find deprecated chunk module usage
    • The chunk module was deprecated in Python 3.11 and removed in Python 3.13. Implement IFF chunk reading manually or use specialized libraries.
  • org.openrewrite.python.migrate.FindCryptModule
    • Find deprecated crypt module usage
    • The crypt module was deprecated in Python 3.11 and removed in Python 3.13. Use bcrypt, argon2-cffi, or passlib instead.
  • org.openrewrite.python.migrate.FindDistutilsUsage
    • Find deprecated distutils module usage
    • Find imports of the deprecated distutils module which was removed in Python 3.12. Migrate to setuptools or other modern build tools.
  • org.openrewrite.python.migrate.FindFunctoolsCmpToKey
    • Find functools.cmp_to_key() usage
    • Find usage of functools.cmp_to_key() which is a Python 2 compatibility function. Consider using a key function directly.
  • org.openrewrite.python.migrate.FindFutureImports
    • Find __future__ imports
    • Find __future__ imports and add a search marker. The RemoveFutureImports recipe automatically removes the imports that are obsolete in Python 3.
  • org.openrewrite.python.migrate.FindImghdrModule
    • Find deprecated imghdr module usage
    • The imghdr module was deprecated in Python 3.11 and removed in Python 3.13. Use filetype, python-magic, or Pillow instead.
  • org.openrewrite.python.migrate.FindImpUsage
    • Find deprecated imp module usage
    • Find imports of the deprecated imp module which was removed in Python 3.12. Migrate to importlib.
  • org.openrewrite.python.migrate.FindLocaleGetdefaultlocale
    • Find deprecated locale.getdefaultlocale() usage
    • locale.getdefaultlocale() was deprecated in Python 3.11. Use locale.setlocale(), locale.getlocale(), or locale.getpreferredencoding(False) instead.
  • org.openrewrite.python.migrate.FindMacpathModule
    • Find removed macpath module usage
    • The macpath module was removed in Python 3.8. Use os.path instead.
  • org.openrewrite.python.migrate.FindMailcapModule
    • Find deprecated mailcap module usage
    • The mailcap module was deprecated in Python 3.11 and removed in Python 3.13. Use mimetypes module for MIME type handling.
  • org.openrewrite.python.migrate.FindMethods
    • Find Python function and method usages
    • Find function and method calls by pattern. Covers standalone functions, class methods, static methods, and constructor calls.
  • org.openrewrite.python.migrate.FindMsilibModule
    • Find deprecated msilib module usage
    • The msilib module was deprecated in Python 3.11 and removed in Python 3.13. Use platform-specific tools for MSI creation.
  • org.openrewrite.python.migrate.FindNisModule
    • Find deprecated nis module usage
    • The nis module was deprecated in Python 3.11 and removed in Python 3.13. There is no direct replacement.
  • org.openrewrite.python.migrate.FindNntplibModule
    • Find deprecated nntplib module usage
    • The nntplib module was deprecated in Python 3.11 and removed in Python 3.13. NNTP is largely obsolete; consider alternatives if needed.
  • org.openrewrite.python.migrate.FindOsPopen
    • Find deprecated os.popen() usage
    • os.popen() has been deprecated since Python 3.6. Use subprocess.run() or subprocess.Popen() instead for better control over process creation and output handling.
  • org.openrewrite.python.migrate.FindOsSpawn
    • Find deprecated os.spawn*() usage
    • The os.spawn*() family of functions are deprecated. Use subprocess.run() or subprocess.Popen() instead.
  • org.openrewrite.python.migrate.FindOssaudiodevModule
    • Find deprecated ossaudiodev module usage
    • The ossaudiodev module was deprecated in Python 3.11 and removed in Python 3.13. There is no direct replacement.
  • org.openrewrite.python.migrate.FindPathlibLinkTo
    • Find deprecated Path.link_to() usage
    • Find usage of Path.link_to() which was deprecated in Python 3.10 and removed in 3.12. Use hardlink_to() instead (note: argument order is reversed). link_to is not a name reserved to pathlib, so this only reports calls whose receiver resolves to a Path; a parse without type attribution reports nothing. Only fires where the receiver's type resolves to pathlib.Path or a subclass.
  • org.openrewrite.python.migrate.FindPipesModule
    • Find deprecated pipes module usage
    • The pipes module was deprecated in Python 3.11 and removed in Python 3.13. Use subprocess with shlex.quote() for shell escaping.
  • org.openrewrite.python.migrate.FindRemovedModules312
    • Find modules removed in Python 3.12
    • Find imports of modules that were removed in Python 3.12, including asynchat, asyncore, and smtpd.
  • org.openrewrite.python.migrate.FindShutilRmtreeOnerror
    • Find deprecated shutil.rmtree(onerror=...) parameter
    • The onerror parameter of shutil.rmtree() was deprecated in Python 3.12 in favor of onexc. The onexc callback receives the exception object directly rather than an exc_info tuple.
  • org.openrewrite.python.migrate.FindSndhdrModule
    • Find deprecated sndhdr module usage
    • The sndhdr module was deprecated in Python 3.11 and removed in Python 3.13. Use filetype or audio libraries like pydub instead.
  • org.openrewrite.python.migrate.FindSocketGetFQDN
    • Find socket.getfqdn() usage
    • Find usage of socket.getfqdn() which can be slow and unreliable. Consider using socket.gethostname() instead.
  • org.openrewrite.python.migrate.FindSpwdModule
    • Find deprecated spwd module usage
    • The spwd module was deprecated in Python 3.11 and removed in Python 3.13. There is no direct replacement.
  • org.openrewrite.python.migrate.FindSslMatchHostname
    • Find deprecated ssl.match_hostname()
    • Find usage of the deprecated ssl.match_hostname() function which was removed in Python 3.12. Use ssl.SSLContext.check_hostname instead.
  • org.openrewrite.python.migrate.FindSunauModule
    • Find deprecated sunau module usage
    • The sunau module was deprecated in Python 3.11 and removed in Python 3.13. Use soundfile or pydub instead.
  • org.openrewrite.python.migrate.FindSysCoroutineWrapper
    • Find removed sys.set_coroutine_wrapper() / sys.get_coroutine_wrapper()
    • sys.set_coroutine_wrapper() and sys.get_coroutine_wrapper() were deprecated in Python 3.7 and removed in Python 3.8.
  • org.openrewrite.python.migrate.FindTelnetlibModule
    • Find deprecated telnetlib module usage
    • The telnetlib module was deprecated in Python 3.11 and removed in Python 3.13. Consider using telnetlib3 from PyPI, direct socket usage, or SSH-based alternatives like paramiko.
  • org.openrewrite.python.migrate.FindTempfileMktemp
    • Find deprecated tempfile.mktemp() usage
    • Find usage of tempfile.mktemp() which is deprecated due to security concerns (race condition). Use mkstemp() or NamedTemporaryFile() instead.
  • org.openrewrite.python.migrate.FindTypes
    • Find Python types
    • Find type references by name. Identifies classes matching a type pattern. In Python, all type definitions use the class keyword, covering regular classes, abstract base classes, protocols, enums, dataclasses, named tuples, typed dicts, and more.
  • org.openrewrite.python.migrate.FindUrllibParseSplitFunctions
    • Find deprecated urllib.parse split functions
    • Find usage of deprecated urllib.parse split functions (splithost, splitport, etc.) removed in Python 3.14. Use urlparse() instead.
  • org.openrewrite.python.migrate.FindUrllibParseToBytes
    • Find deprecated urllib.parse.to_bytes() usage
    • Find usage of urllib.parse.to_bytes() which was deprecated in Python 3.8 and removed in 3.14. Use str.encode() directly.
  • org.openrewrite.python.migrate.FindUuModule
    • Find deprecated uu module usage
    • The uu module was deprecated in Python 3.11 and removed in Python 3.13. Use base64 module instead for encoding binary data.
  • org.openrewrite.python.migrate.FindXdrlibModule
    • Find deprecated xdrlib module usage
    • The xdrlib module was deprecated in Python 3.11 and removed in Python 3.13. Use struct module for binary packing/unpacking.
  • org.openrewrite.python.migrate.MigrateAsyncioCoroutine
    • Migrate @asyncio.coroutine to async def
    • Migrate functions using the deprecated @asyncio.coroutine decorator to use async def syntax. Also transforms yield from to await. The decorator was removed in Python 3.11. A function whose body has a bare yield is left alone, since it would become an async generator.
  • org.openrewrite.python.migrate.MigrateAvroPython3ToAvro
    • Migrate the deprecated avro-python3 package to avro
    • Replace the deprecated avro-python3 distribution with its maintained successor, Apache avro. Both install the same top-level avro import package, so module imports are unchanged, but avro-python3's avro.schema.Parse was renamed to the lowercase avro.schema.parse (and Parse removed) in avro 1.11+, so that reference is rewritten. The dependency swap is applied by org.openrewrite.python.ChangeDependency.
  • org.openrewrite.python.migrate.MigrateBackoffToTenacity
    • Migrate backoff to tenacity
    • Replace backoff's retry decorators with tenacity's @retry, and add the tenacity dependency to exactly the projects where a decorator converted -- a project whose every decorator needs a hand migration gains no dependency, and neither does a repository this leaves unchanged. backoff itself stays, because a decorator tenacity cannot reproduce still needs it. Run org.openrewrite.python.migrate.FindBackoffDecoratorsNotMigrated for the decorators left to migrate by hand, then drop backoff once that list is empty.
  • org.openrewrite.python.migrate.MigrateToPyprojectToml
    • Migrate to pyproject.toml
    • Migrate Python projects from requirements.txt and/or setup.cfg to pyproject.toml with hatchling build backend.
  • org.openrewrite.python.migrate.RemoveFutureImports
    • Remove obsolete __future__ imports
    • Remove from __future__ import ... statements for features that are enabled by default in Python 3. The search-only FindFutureImports recipe reports all __future__ imports, including annotations, which this recipe keeps.
  • org.openrewrite.python.migrate.ReplaceArrayFromstring
    • Replace array.fromstring() with array.frombytes()
    • Replace fromstring() with frombytes() on array objects. The fromstring() method was deprecated in Python 3.2 and removed in 3.14. Only fires where the receiver's type resolves to array.array or a subclass.
  • org.openrewrite.python.migrate.ReplaceArrayTostring
    • Replace array.tostring() with array.tobytes()
    • Replace tostring() with tobytes() on array objects. The tostring() method was deprecated in Python 3.2 and removed in 3.14. Only fires where the receiver's type resolves to array.array or a subclass.
  • org.openrewrite.python.migrate.ReplaceAstBytes
    • Replace ast.Bytes with ast.Constant
    • The ast.Bytes node type was deprecated in Python 3.8 and removed in Python 3.14. Replace with ast.Constant and check isinstance(node.value, bytes).
  • org.openrewrite.python.migrate.ReplaceAstEllipsis
    • Replace ast.Ellipsis with ast.Constant
    • The ast.Ellipsis node type was deprecated in Python 3.8 and removed in Python 3.14. Replace with ast.Constant and check node.value is ....
  • org.openrewrite.python.migrate.ReplaceAstNameConstant
    • Replace ast.NameConstant with ast.Constant
    • The ast.NameConstant node type was deprecated in Python 3.8 and removed in Python 3.14. Replace with ast.Constant and check node.value in (True, False, None).
  • org.openrewrite.python.migrate.ReplaceAstNum
    • Replace ast.Num with ast.Constant
    • The ast.Num node type was deprecated in Python 3.8 and removed in Python 3.14. Replace with ast.Constant and check isinstance(node.value, (int, float, complex)).
  • org.openrewrite.python.migrate.ReplaceAstStr
    • Replace ast.Str with ast.Constant
    • The ast.Str node type was deprecated in Python 3.8 and removed in Python 3.14. Replace with ast.Constant and check isinstance(node.value, str).
  • org.openrewrite.python.migrate.ReplaceBackoffDecoratorsWithTenacity
    • Replace backoff decorators with tenacity
    • Rewrite @backoff.on_exception and @backoff.on_predicate as tenacity's @retry, mapping max_tries and max_time to stop strategies and backoff.expo/backoff.constant to the wait strategy matching backoff's jitter setting. reraise=True is added so an exhausted decorator keeps raising the original exception rather than tenacity's RetryError. Decorators whose behaviour tenacity cannot reproduce are left untouched: backoff.fibo and backoff.runtime, a */** argument, the on_backoff, on_giveup and on_success handlers, giveup, and a max_tries or interval written as a lambda, which backoff evaluates per retry. A callable passed by name in one of those cannot be told from a value, so check those by hand. Run org.openrewrite.python.migrate.FindBackoffDecoratorsNotMigrated to list those. Backoff's logging configuration is dropped, because tenacity logs nothing by default; the backoff import and dependency are kept when any usage remains.
  • org.openrewrite.python.migrate.ReplaceCalendarConstants
    • Replace deprecated calendar constants with uppercase
    • Replace deprecated mixed-case calendar constants like calendar.January with their uppercase equivalents like calendar.JANUARY. The mixed-case constants were deprecated in Python 3.12.
  • org.openrewrite.python.migrate.ReplaceCgiParseQs
    • Replace cgi.parse_qs() with urllib.parse.parse_qs()
    • cgi.parse_qs() was removed in Python 3.8. Use urllib.parse.parse_qs() instead.
  • org.openrewrite.python.migrate.ReplaceCgiParseQsl
    • Replace cgi.parse_qsl() with urllib.parse.parse_qsl()
    • cgi.parse_qsl() was removed in Python 3.8. Use urllib.parse.parse_qsl() instead.
  • org.openrewrite.python.migrate.ReplaceCollectionsAbcImports
    • Replace collections ABC imports with collections.abc
    • Migrate deprecated abstract base class imports from collections to collections.abc. These imports were deprecated in Python 3.3 and removed in Python 3.10.
  • org.openrewrite.python.migrate.ReplaceConditionNotifyAll
    • Replace Condition.notifyAll() with Condition.notify_all()
    • Replace notifyAll() method calls with notify_all(). The camelCase version was deprecated in Python 3.10 and removed in 3.12. Only fires where the receiver's type resolves to threading.Condition or a subclass.
  • org.openrewrite.python.migrate.ReplaceConfigparserReadfp
    • Replace ConfigParser.readfp() with read_file()
    • The ConfigParser.readfp() method was deprecated in Python 3.2 and removed in Python 3.13. Replace with read_file(). Only fires where the receiver's type resolves to configparser.RawConfigParser or a subclass.
  • org.openrewrite.python.migrate.ReplaceConfigparserSafeConfigParser
    • Replace configparser.SafeConfigParser with ConfigParser
    • The configparser.SafeConfigParser class was deprecated in Python 3.2 and removed in Python 3.12. Replace with configparser.ConfigParser.
  • org.openrewrite.python.migrate.ReplaceDatetimeUtcFromTimestamp
    • Replace datetime.utcfromtimestamp() with datetime.fromtimestamp(ts, UTC)
    • The datetime.utcfromtimestamp() method is deprecated in Python 3.12. Replace it with datetime.fromtimestamp(ts, UTC), importing UTC from datetime where the name is not already in scope. The result is timezone-aware where utcfromtimestamp() was naive, so stored or compared values may need migrating alongside the call sites.
  • org.openrewrite.python.migrate.ReplaceDatetimeUtcNow
    • Replace datetime.utcnow() with datetime.now(UTC)
    • The datetime.utcnow() method is deprecated in Python 3.12. Replace it with datetime.now(UTC), importing UTC from datetime where the name is not already in scope. The result is timezone-aware where utcnow() was naive, so stored or compared values may need migrating alongside the call sites.
  • org.openrewrite.python.migrate.ReplaceDistutilsVersion
    • Replace deprecated distutils.version usage
    • Detect usage of deprecated distutils.version.LooseVersion and distutils.version.StrictVersion. These should be migrated to packaging.version.Version. Note: Manual migration is required as packaging.version.Version is not a drop-in replacement.
  • org.openrewrite.python.migrate.ReplaceElementGetchildren
    • Replace Element.getchildren() with list(element)
    • Replace getchildren() with list(element) on XML Element objects. Deprecated in Python 3.9. Only fires where the receiver's type resolves to xml.etree.ElementTree.Element or a subclass.
  • org.openrewrite.python.migrate.ReplaceElementGetiterator
    • Replace Element.getiterator() with Element.iter()
    • Replace getiterator() with iter() on XML Element objects. The getiterator() method was deprecated in Python 3.9. Only fires where the receiver's type resolves to xml.etree.ElementTree.Element or a subclass.
  • org.openrewrite.python.migrate.ReplaceEventIsSet
    • Replace Event.isSet() with Event.is_set()
    • Replace isSet() method calls with is_set(). The camelCase version was deprecated in Python 3.10 and removed in 3.12. Only fires where the receiver's type resolves to threading.Event or a subclass.
  • org.openrewrite.python.migrate.ReplaceGettextDeprecations
    • Replace deprecated gettext l*gettext() functions
    • Replace deprecated gettext functions like lgettext() with their modern equivalents like gettext(). The l*gettext() functions were removed in Python 3.11.
  • org.openrewrite.python.migrate.ReplaceHtmlParserUnescape
    • Replace HTMLParser.unescape() with html.unescape()
    • HTMLParser.unescape() was removed in Python 3.9. Use html.unescape() instead. Only fires where the parser's type resolves, and leaves the call alone where html already names something other than the module.
  • org.openrewrite.python.migrate.ReplaceLocaleResetlocale
    • Replace locale.resetlocale() with locale.setlocale(LC_ALL, '')
    • The locale.resetlocale() function was deprecated in Python 3.11 and removed in Python 3.13. Replace with locale.setlocale(locale.LC_ALL, '').
  • org.openrewrite.python.migrate.ReplacePercentFormatWithFString
    • Replace % formatting with f-string
    • Replace &quot;...&quot; % (...) expressions with f-strings (Python 3.6+). Only converts %s and %r specifiers where the format string is a literal and the conversion is safe. A single operand that is not a tuple literal must have a type that resolves to a non-tuple, such as str or int, since a tuple would be spread over the specifiers.
  • org.openrewrite.python.migrate.ReplacePkgutilFindLoader
    • Replace pkgutil.find_loader() with importlib.util.find_spec()
    • The pkgutil.find_loader() function was deprecated in Python 3.12. Replace with importlib.util.find_spec(). Note: returns ModuleSpec, use .loader for loader.
  • org.openrewrite.python.migrate.ReplacePkgutilGetLoader
    • Replace pkgutil.get_loader() with importlib.util.find_spec()
    • The pkgutil.get_loader() function was deprecated in Python 3.12. Replace with importlib.util.find_spec(). Note: returns ModuleSpec, use .loader for loader.
  • org.openrewrite.python.migrate.ReplacePlatformPopen
    • Replace platform.popen() with subprocess.check_output()
    • platform.popen() was removed in Python 3.8. Use subprocess.check_output(cmd, shell=True) instead. Only the single-argument form is rewritten, since mode and bufsize have no check_output equivalent.
  • org.openrewrite.python.migrate.ReplaceReTemplate
    • Replace re.template() with re.compile() and flag re.TEMPLATE/re.T
    • re.template() was deprecated in Python 3.11 and removed in 3.13. Calls are auto-replaced with re.compile(). re.TEMPLATE/re.T flags have no direct replacement and are flagged for manual review.
  • org.openrewrite.python.migrate.ReplaceStrFormatWithFString
    • Replace str.format() with f-string
    • Replace &quot;...&quot;.format(...) calls with f-strings (Python 3.6+). Only converts cases where the format string is a literal and the conversion is safe.
  • org.openrewrite.python.migrate.ReplaceSysLastExcInfo
    • Replace sys.last_type / sys.last_value / sys.last_traceback with sys.last_exc
    • sys.last_type, sys.last_value, and sys.last_traceback were deprecated in Python 3.12. Replace them with their sys.last_exc-based equivalents: type(sys.last_exc), sys.last_exc, and sys.last_exc.__traceback__ respectively.
  • org.openrewrite.python.migrate.ReplaceTarfileFilemode
    • Replace tarfile.filemode with stat.filemode
    • tarfile.filemode was removed in Python 3.8. Use stat.filemode() instead.
  • org.openrewrite.python.migrate.ReplaceThreadGetName
    • Replace Thread.getName() with Thread.name
    • Replace getName() method calls with the name property. Deprecated in Python 3.10, removed in 3.12. Only fires where the receiver's type resolves to threading.Thread or a subclass.
  • org.openrewrite.python.migrate.ReplaceThreadIsAlive
    • Replace Thread.isAlive() with Thread.is_alive()
    • Replace isAlive() method calls with is_alive(). Deprecated in Python 3.1 and removed in 3.9. Only fires where the receiver's type resolves to threading.Thread or a subclass.
  • org.openrewrite.python.migrate.ReplaceThreadIsDaemon
    • Replace Thread.isDaemon() with Thread.daemon
    • Replace isDaemon() method calls with the daemon property. Deprecated in Python 3.10, removed in 3.12. Only fires where the receiver's type resolves to threading.Thread or a subclass.
  • org.openrewrite.python.migrate.ReplaceThreadSetDaemon
    • Replace Thread.setDaemon() with Thread.daemon = ...
    • Replace setDaemon() method calls with daemon property assignment. Deprecated in Python 3.10, removed in 3.12. Only fires where the receiver's type resolves to threading.Thread or a subclass.
  • org.openrewrite.python.migrate.ReplaceThreadSetName
    • Replace Thread.setName() with Thread.name = ...
    • Replace setName() method calls with name property assignment. Deprecated in Python 3.10, removed in 3.12. Only fires where the receiver's type resolves to threading.Thread or a subclass.
  • org.openrewrite.python.migrate.ReplaceThreadingActiveCount
    • Replace threading.activeCount() with threading.active_count()
    • Replace threading.activeCount() with threading.active_count(). The camelCase version was deprecated in Python 3.10 and removed in 3.12.
  • org.openrewrite.python.migrate.ReplaceThreadingCurrentThread
    • Replace threading.currentThread() with threading.current_thread()
    • Replace threading.currentThread() with threading.current_thread(). The camelCase version was deprecated in Python 3.10 and removed in 3.12.
  • org.openrewrite.python.migrate.ReplaceTypingCallableWithCollectionsAbcCallable
    • Replace typing.Callable with collections.abc.Callable
    • PEP 585 deprecated typing.Callable in Python 3.9. Replace with collections.abc.Callable for type annotations.
  • org.openrewrite.python.migrate.ReplaceTypingDictWithDict
    • Replace typing.Dict with dict
    • PEP 585 deprecated typing.Dict in Python 3.9. Replace it with the built-in dict wherever a type is expected, including class base lists, where either spelling subclasses dict. Applies inside if TYPE_CHECKING: blocks as well; the built-in generic is valid at runtime from Python 3.9 on, so no from __future__ import annotations is needed. References in a value position are left alone: typing.Dict and dict are distinct objects, so substituting one for the other where the name is used as a value would change behaviour.
  • org.openrewrite.python.migrate.ReplaceTypingFrozenSetWithFrozenset
    • Replace typing.FrozenSet with frozenset
    • PEP 585 deprecated typing.FrozenSet in Python 3.9. Replace it with the built-in frozenset wherever a type is expected, including class base lists, where either spelling subclasses frozenset. Applies inside if TYPE_CHECKING: blocks as well; the built-in generic is valid at runtime from Python 3.9 on, so no from __future__ import annotations is needed. References in a value position are left alone: typing.FrozenSet and frozenset are distinct objects, so substituting one for the other where the name is used as a value would change behaviour.
  • org.openrewrite.python.migrate.ReplaceTypingListWithList
    • Replace typing.List with list
    • PEP 585 deprecated typing.List in Python 3.9. Replace it with the built-in list wherever a type is expected, including class base lists, where either spelling subclasses list. Applies inside if TYPE_CHECKING: blocks as well; the built-in generic is valid at runtime from Python 3.9 on, so no from __future__ import annotations is needed. References in a value position are left alone: typing.List and list are distinct objects, so substituting one for the other where the name is used as a value would change behaviour.
  • org.openrewrite.python.migrate.ReplaceTypingOptionalWithUnion
    • Replace typing.Optional[X] with X | None
    • PEP 604 introduced the | operator for union types in Python 3.10. Replace Optional[X] with the more concise X | None syntax. Applies inside if TYPE_CHECKING: blocks as well; X | None is valid at runtime from Python 3.10 on, so no from __future__ import annotations is needed.
  • org.openrewrite.python.migrate.ReplaceTypingSetWithSet
    • Replace typing.Set with set
    • PEP 585 deprecated typing.Set in Python 3.9. Replace it with the built-in set wherever a type is expected, including class base lists, where either spelling subclasses set. Applies inside if TYPE_CHECKING: blocks as well; the built-in generic is valid at runtime from Python 3.9 on, so no from __future__ import annotations is needed. References in a value position are left alone: typing.Set and set are distinct objects, so substituting one for the other where the name is used as a value would change behaviour.
  • org.openrewrite.python.migrate.ReplaceTypingText
    • Replace typing.Text with str
    • typing.Text is deprecated as of Python 3.11. It was an alias for str for Python 2/3 compatibility. Replace with str.
  • org.openrewrite.python.migrate.ReplaceTypingTupleWithTuple
    • Replace typing.Tuple with tuple
    • PEP 585 deprecated typing.Tuple in Python 3.9. Replace it with the built-in tuple wherever a type is expected, including class base lists, where either spelling subclasses tuple. Applies inside if TYPE_CHECKING: blocks as well; the built-in generic is valid at runtime from Python 3.9 on, so no from __future__ import annotations is needed. References in a value position are left alone: typing.Tuple and tuple are distinct objects, so substituting one for the other where the name is used as a value would change behaviour.
  • org.openrewrite.python.migrate.ReplaceTypingTypeWithType
    • Replace typing.Type with type
    • PEP 585 deprecated typing.Type in Python 3.9. Replace it with the built-in type wherever a type is expected, including class base lists, where either spelling subclasses type. Applies inside if TYPE_CHECKING: blocks as well; the built-in generic is valid at runtime from Python 3.9 on, so no from __future__ import annotations is needed. References in a value position are left alone: typing.Type and type are distinct objects, so substituting one for the other where the name is used as a value would change behaviour.
  • org.openrewrite.python.migrate.ReplaceTypingUnionWithPipe
    • Replace typing.Union[X, Y] with X | Y
    • PEP 604 introduced the | operator for union types in Python 3.10. Replace Union[X, Y, ...] with the more concise X | Y | ... syntax. Applies inside if TYPE_CHECKING: blocks as well; X | Y is valid at runtime from Python 3.10 on, so no from __future__ import annotations is needed.
  • org.openrewrite.python.migrate.ReplaceUnittestDeprecatedAliases
    • Replace deprecated unittest method aliases
    • Replace deprecated unittest.TestCase method aliases like assertEquals with their modern equivalents like assertEqual. These aliases were removed in Python 3.11/3.12. Only fires where the receiver's type resolves to unittest.TestCase or a subclass.
  • org.openrewrite.python.migrate.UpgradePythonCloudFormationRuntime
    • Upgrade Python runtime in CloudFormation templates
    • Update Python Lambda runtimes in CloudFormation and SAM templates to a target version. Bumps Runtime: python3.x properties (AWS::Lambda::Function, AWS::Serverless::Function, and the SAM Globals section) and python3.x entries in CompatibleRuntimes lists of Lambda layer versions. Indirection is followed: a YAML anchor aliased from a runtime value is bumped where it is defined, and a parameter referenced from a runtime value (!Ref or Ref:) has its Default and any AllowedValues bumped. Templates are recognized by content — AWSTemplateFormatVersion, an AWS:: Transform, or Resources with AWS:: resource types — so any YAML template is updated regardless of its file name or location. Only runtimes older than the target are changed; a runtime already on a newer version is left as-is.
  • org.openrewrite.python.migrate.UpgradePythonDockerImage
    • Upgrade Python Docker base image
    • Update the Python version of Python images in Dockerfiles to a target version: FROM python:&lt;version&gt; base images and COPY --from=&lt;python image&gt; / ADD --from=&lt;python image&gt; stage references (e.g. COPY --from=registry.example.com/approved-images/python:3.10-ubuntu22.04 /usr /usr). Tag suffixes such as -slim are preserved, any patch component is dropped, and an image already on a newer version is left as-is. --from references to named build stages are not image references and are left untouched.
  • org.openrewrite.python.migrate.UpgradePythonVersion
    • Upgrade Python version in project files
    • Update the Python version referenced in project metadata and packaging files to a target version. Updates Pipfile (python_version / python_full_version), pyproject.toml ([project] requires-python and Poetry's [tool.poetry.dependencies] python), setup.cfg (python_requires), and .python-version files. When a lock file (uv.lock or Pipfile.lock) is present, it is regenerated natively to match, without executing the package manager or requiring one on PATH. Only references older than the target are changed; a file already on a newer version is left as-is. Dockerfile base images are handled separately by UpgradePythonDockerImage, CloudFormation/SAM templates by UpgradePythonCloudFormationRuntime, Mend .whitesource files by UpgradePythonWhitesourceConfig, and requirements.txt is not modified because it pins package versions, not the interpreter version.
  • org.openrewrite.python.migrate.UpgradePythonVersionTo310
    • Upgrade Python version in project files to 3.10
    • Update the Python version referenced in pyproject.toml, Pipfile, setup.cfg, .python-version, Dockerfile base images, CloudFormation/SAM template runtimes, and Mend .whitesource files to 3.10.
  • org.openrewrite.python.migrate.UpgradePythonVersionTo311
    • Upgrade Python version in project files to 3.11
    • Update the Python version referenced in pyproject.toml, Pipfile, setup.cfg, .python-version, Dockerfile base images, CloudFormation/SAM template runtimes, and Mend .whitesource files to 3.11.
  • org.openrewrite.python.migrate.UpgradePythonVersionTo312
    • Upgrade Python version in project files to 3.12
    • Update the Python version referenced in pyproject.toml, Pipfile, setup.cfg, .python-version, Dockerfile base images, CloudFormation/SAM template runtimes, and Mend .whitesource files to 3.12.
  • org.openrewrite.python.migrate.UpgradePythonVersionTo313
    • Upgrade Python version in project files to 3.13
    • Update the Python version referenced in pyproject.toml, Pipfile, setup.cfg, .python-version, Dockerfile base images, CloudFormation/SAM template runtimes, and Mend .whitesource files to 3.13.
  • org.openrewrite.python.migrate.UpgradePythonVersionTo314
    • Upgrade Python version in project files to 3.14
    • Update the Python version referenced in pyproject.toml, Pipfile, setup.cfg, .python-version, Dockerfile base images, CloudFormation/SAM template runtimes, and Mend .whitesource files to 3.14.
  • org.openrewrite.python.migrate.UpgradePythonVersionTo38
    • Upgrade Python version in project files to 3.8
    • Update the Python version referenced in pyproject.toml, Pipfile, setup.cfg, .python-version, Dockerfile base images, CloudFormation/SAM template runtimes, and Mend .whitesource files to 3.8.
  • org.openrewrite.python.migrate.UpgradePythonVersionTo39
    • Upgrade Python version in project files to 3.9
    • Update the Python version referenced in pyproject.toml, Pipfile, setup.cfg, .python-version, Dockerfile base images, CloudFormation/SAM template runtimes, and Mend .whitesource files to 3.9.
  • org.openrewrite.python.migrate.UpgradePythonWhitesourceConfig
    • Upgrade Python version in Mend .whitesource files
    • Update Python version references in Mend (formerly WhiteSource) .whitesource repository configuration files to a target version. Bumps python&lt;MAJOR&gt;&lt;MINOR&gt; and python&lt;MAJOR&gt;.&lt;MINOR&gt; tokens in the settingsInheritedFrom value (e.g. &quot;org/whitesource-config@python310&quot; -> ...@python312) and in the python.path scan setting (a Unified Agent parameter, so both bare executable names such as python3.9 and full paths such as /usr/bin/python3.9 are covered). Only versions older than the target are changed; a version already newer is left as-is.
  • org.openrewrite.python.migrate.UpgradeToPython310
    • Upgrade to Python 3.10
    • Migrate deprecated APIs and adopt new syntax for Python 3.10 compatibility. This includes adopting PEP 604 union type syntax (X | Y) and other modernizations between Python 3.9 and 3.10.
  • org.openrewrite.python.migrate.UpgradeToPython311
    • Upgrade to Python 3.11
    • Migrate deprecated and removed APIs for Python 3.11 compatibility. This includes handling removed modules, deprecated functions, and API changes between Python 3.10 and 3.11.
  • org.openrewrite.python.migrate.UpgradeToPython312
    • Upgrade to Python 3.12
    • Migrate deprecated and removed APIs for Python 3.12 compatibility. This includes detecting usage of the removed imp module and other legacy modules that were removed in Python 3.12.
  • org.openrewrite.python.migrate.UpgradeToPython313
    • Upgrade to Python 3.13
    • Migrate deprecated and removed APIs for Python 3.13 compatibility. This includes detecting usage of modules removed in PEP 594 ('dead batteries'), other API changes between Python 3.12 and 3.13, and bumping third-party dependencies (ruff, avro-python3) whose pinned releases do not install cleanly on Python 3.13.
  • org.openrewrite.python.migrate.UpgradeToPython314
    • Upgrade to Python 3.14
    • Migrate deprecated and removed APIs for Python 3.14 compatibility. This includes replacing deprecated AST node types with ast.Constant and other API changes between Python 3.13 and 3.14.
  • org.openrewrite.python.migrate.UpgradeToPython38
    • Upgrade to Python 3.8
    • Migrate deprecated APIs and detect legacy patterns for Python 3.8 compatibility.
  • org.openrewrite.python.migrate.UpgradeToPython39
    • Upgrade to Python 3.9
    • Migrate deprecated APIs for Python 3.9 compatibility. This includes PEP 585 built-in generics, removed base64 functions, and deprecated XML Element methods, and adopts the dict union operator and str.removeprefix()/removesuffix().
  • org.openrewrite.python.migrate.langchain.FindDeprecatedLangchainAgents
    • Find deprecated LangChain agent patterns
    • Find usage of deprecated LangChain agent patterns including initialize_agent, AgentExecutor, and LLMChain. These were deprecated in LangChain v0.2 and removed in v1.0.
  • org.openrewrite.python.migrate.langchain.FindLangchainCreateReactAgent
    • Find create_react_agent usage (replace with create_agent)
    • Find from langgraph.prebuilt import create_react_agent which should be replaced with from langchain.agents import create_agent in LangChain v1.0.
  • org.openrewrite.python.migrate.langchain.ReplaceLangchainClassicImports
    • Replace langchain legacy imports with langchain_classic
    • Migrate legacy chain, retriever, and indexing imports from langchain to langchain_classic. These were moved in LangChain v1.0.
  • org.openrewrite.python.migrate.langchain.ReplaceLangchainCommunityImports
    • Replace langchain imports with langchain_community
    • Migrate third-party integration imports from langchain to langchain_community. These integrations were moved in LangChain v0.2.
  • org.openrewrite.python.migrate.langchain.ReplaceLangchainProviderImports
    • Replace langchain_community imports with provider packages
    • Migrate provider-specific imports from langchain_community to dedicated provider packages like langchain_openai, langchain_anthropic, etc.
  • org.openrewrite.python.migrate.langchain.UpgradeToLangChain02
    • Upgrade to LangChain 0.2
    • Migrate to LangChain 0.2 by updating imports from langchain to langchain_community and provider-specific packages.
  • org.openrewrite.python.migrate.langchain.UpgradeToLangChain1
    • Upgrade to LangChain 1.0
    • Migrate to LangChain 1.0 by applying all v0.2 migrations and then moving legacy functionality to langchain_classic.
  • org.openrewrite.python.migrate.pandas.UpgradeToPandas20
    • Upgrade to pandas 2.0
    • Migrate code that uses APIs removed in pandas 2.0, such as DataFrame.append(), which becomes pd.concat().
  • org.openrewrite.python.migrate.pydantic.FindDeprecatedJsonEncoders
    • Find deprecated json_encoders config option
    • Pydantic deprecated the json_encoders option in ConfigDict. Its replacements (@field_serializer / @model_serializer or Annotated[..., PlainSerializer(...)]) require restructuring, so this recipe flags its use for review.
  • org.openrewrite.python.migrate.pydantic.FindDeprecatedSchemaGenerator
    • Find deprecated schema_generator config option
    • Pydantic 2.10 deprecated the schema_generator option in ConfigDict. It has no public replacement yet, so this recipe flags its use for review.
  • org.openrewrite.python.migrate.pydantic.FindEvalTypeBackportUsage
    • Find eval_type_backport usage removed in Pydantic 2.14
    • Pydantic 2.14 removed its support for the eval_type_backport package. With the Python 3.10 minimum it is no longer needed. This recipe flags import eval_type_backport and from eval_type_backport import ... for review.
  • org.openrewrite.python.migrate.pydantic.FindModelValidatorAfterClassmethod
    • Find @model_validator(mode='after') on a classmethod
    • Pydantic 2.12 deprecated @model_validator with mode='after' on a classmethod; the implicit classmethod conversion for after model validators is removed in V3. Such validators should be instance methods (self, no @classmethod). This recipe flags the decorator for review, since the rewrite is not safe to mechanize. field_validator is unaffected.
  • org.openrewrite.python.migrate.pydantic.FindSerializeAsAnyUsage
    • Find serialize_as_any usage affected by the Pydantic 2.12 unification
    • Pydantic 2.12 unified the serialize_as_any flag with the SerializeAsAny annotation, which can change serialization output versus 2.11. This recipe flags serialize_as_any= on model_dump / model_dump_json (and TypeAdapter.dump_python / dump_json) for review, since there is no safe mechanical rewrite. Only fires where the receiver's type resolves to pydantic.BaseModel, pydantic.TypeAdapter or a subclass.
  • org.openrewrite.python.migrate.pydantic.RemoveEllipsisFromField
    • Remove ... (Ellipsis) from Field()
    • Pydantic 2.10 recommends against using Ellipsis (...) with Field to mark a field as required, as it does not play well with static type checkers. Rewrite Field(...) to Field() (and Field(..., x=y) to Field(x=y)), keeping the remaining arguments. Only calls resolving to pydantic.fields.Field are rewritten.
  • org.openrewrite.python.migrate.pydantic.ReplaceFinalFieldWithClassVar
    • Replace Final model fields with a default with ClassVar
    • Pydantic 2.11 deprecates annotating a model field as Final with a default value (such fields were treated as class variables). Replace Final[X] = default with ClassVar[X] = default, which preserves the existing class-variable behavior and is the replacement Pydantic recommends.
  • org.openrewrite.python.migrate.pydantic.ReplaceModelFieldsInstanceAccess
    • Replace instance access of model_fields / model_computed_fields
    • Pydantic 2.11 deprecated accessing model_fields and model_computed_fields on a model instance; these are removed in Pydantic 3.0. Replace &lt;instance&gt;.model_fields with type(&lt;instance&gt;).model_fields (and likewise for model_computed_fields) when the receiver resolves to a Pydantic model, so the attribute is accessed on the class. Class access and cls access are left untouched.
  • org.openrewrite.python.migrate.pydantic.ReplacePopulateByNameWithValidateByName
    • Replace populate_by_name with validate_by_name
    • Pydantic 2.11 introduced validate_by_name as the equivalent of populate_by_name, which is pending deprecation in Pydantic V3. Rename ConfigDict(populate_by_name=...) to ConfigDict(validate_by_name=...). This is behavior-preserving (validate_by_alias defaults to True) and future-proofs the configuration.
  • org.openrewrite.python.migrate.pydantic.UpgradeToPydantic210
    • Upgrade to Pydantic 2.10
    • Flag and migrate code affected by deprecations introduced in Pydantic 2.10, such as the deprecated schema_generator config option and the discouraged Field(...) Ellipsis form. Also flags the deprecated json_encoders config option.
  • org.openrewrite.python.migrate.pydantic.UpgradeToPydantic211
    • Upgrade to Pydantic 2.11
    • Migrate code affected by deprecations introduced in Pydantic 2.11 (and 2.10). Rewrites instance access of model_fields / model_computed_fields to class access, rewrites Final model fields with default values to ClassVar, and renames populate_by_name to validate_by_name.
  • org.openrewrite.python.migrate.pydantic.UpgradeToPydantic212
    • Upgrade to Pydantic 2.12
    • Migrate code affected by changes introduced in Pydantic 2.12 (and 2.10/2.11). Flags serialize_as_any usage affected by the 2.12 unification with the SerializeAsAny annotation.
  • org.openrewrite.python.migrate.pydantic.UpgradeToPydantic213
    • Upgrade to Pydantic 2.13
    • Migrate code for Pydantic 2.13. Pydantic 2.13 introduced no new deprecations (an additive release), so this applies all Pydantic 2.12 migrations (which chain back to 2.10).
  • org.openrewrite.python.migrate.pydantic.UpgradeToPydantic214
    • Upgrade to Pydantic 2.14
    • Migrate code affected by changes introduced in Pydantic 2.14 (and 2.10-2.13). Flags eval_type_backport usage, whose support 2.14 removed. Note: 2.14 is in prerelease; verify against the 2.14.0 GA release.

rewrite-netty​

License: Apache License Version 2.0

11 recipes

rewrite-nodejs​

License: Moderne Proprietary License

15 recipes

  • org.openrewrite.nodejs.migrate.UpgradeNodeVersion
    • Upgrade Node.js version in version files
    • Increases the Node.js version in .nvmrc and .node-version files. Major versions (20, v20) and pinned versions (20.11.0) become the target major, and LTS codenames (lts/iron) become the target's codename. Floating aliases such as lts/* and node are left alone. Never decreases the version.
  • org.openrewrite.nodejs.search.DatabaseInteractionInsights
    • Javascript database interaction library insights
    • Discover which popular javascript database interaction libraries (Sequelize, TypeORM, Mongoose, etc.) are being used in your projects.
  • org.openrewrite.nodejs.search.FindNodeProjects
    • Find Node.js projects
    • Find Node.js projects and summarize data about them.
  • org.openrewrite.nodejs.search.FormHandlingInsights
    • Javascript form handling library insights
    • Discover which popular javascript form handling libraries (Formik, React Hook Form, Yup, etc.) are being used in your projects.
  • org.openrewrite.nodejs.search.LintingFormattingInsights
    • Javascript linting & formatting library insights
    • Discover which popular javascript linting and formatting libraries (ESLint, Prettier, Stylelint, etc.) are being used in your projects.
  • org.openrewrite.nodejs.search.RealTimeCommunicationInsights
    • Javascript real-time communication library insights
    • Discover which popular javascript real-time communication libraries (Socket.io, Ws, SockJS, etc.) are being used in your projects.
  • org.openrewrite.nodejs.search.SecurityInsights
    • Javascript security library insights
    • Discover which popular javascript security libraries (Helmet, Cors, Bcrypt, etc.) are being used in your projects.
  • org.openrewrite.nodejs.search.ServerSideFrameworksInsights
    • Javascript server-side frameworks insights
    • Discover which popular javascript server-side frameworks (Express, Koa, Hapi, etc.) are being used in your projects.
  • org.openrewrite.nodejs.search.StateManagementInsights
    • Javascript state management library insights
    • Discover which popular javascript state management libraries (Redux, MobX, Vuex, etc.) are being used in your projects.
  • org.openrewrite.nodejs.search.TaskRunnersBuildToolsInsights
    • Javascript task runners & build tools insights
    • Discover which popular javascript task runners and build tools (Webpack, Parcel, Gulp, etc.) are being used in your projects.
  • org.openrewrite.nodejs.search.TestingInsights
    • Javascript testing library insights
    • Discover which popular javascript testing libraries (Jest, Mocha, Chai, etc.) are being used in your projects.
  • org.openrewrite.nodejs.search.UIInsights
    • Javascript UI library insights
    • Discover which popular javascript UI libraries (React, Vue.js, Angular, etc.) are being used in your projects.
  • org.openrewrite.nodejs.search.UtilityInsights
    • Javascript utility library insights
    • Discover which popular javascript utility libraries (Lodash, Moment.js, Date-fns, etc.) are being used in your projects.
  • org.openrewrite.nodejs.security.DependencyVulnerabilityCheck
    • Find and fix vulnerable npm dependencies
    • This software composition analysis (SCA) tool detects and upgrades dependencies with publicly disclosed vulnerabilities. This recipe both generates a report of vulnerable dependencies and upgrades to newer versions with fixes. This recipe by default only upgrades to the latest patch version. If a minor or major upgrade is required to reach the fixed version, this can be controlled using the maximumUpgradeDelta option. Vulnerability information comes from the GitHub Security Advisory Database, which aggregates vulnerability data from several public databases. ## Customizing Vulnerability Data Extend this recipe and override baselineVulnerabilities(ctx) to replace the bundled advisory database, or override supplementalVulnerabilities(ctx) to add organisation-specific advisories alongside the bundled data.
  • org.openrewrite.nodejs.security.RemoveRedundantOverrides
    • Remove redundant dependency overrides
    • Removes overrides/resolutions from package.json that are redundant because the dependency tree already resolves to the overridden version (or higher) without the override. For each project, the recipe resolves the dependency closure with all overrides stripped and compares the resolved versions against the original override pins. Overrides matching or below the natural resolution are dropped along with any parallel //overrides, //resolutions, or //pnpm.overrides comment entries.

rewrite-okhttp​

License: Moderne Source Available License

10 recipes

rewrite-openapi​

License: Apache License Version 2.0

17 recipes

rewrite-pmd​

License: Moderne Source Available License

6 recipes

  • org.openrewrite.java.pmd.AddPmdRule
    • Add a PMD rule to a ruleset
    • Adds a &lt;rule ref=&quot;...&quot;/&gt; reference to PMD ruleset XML files that do not have one yet. When the ruleset already pulls in the whole ruleset file the rule lives in, the rule is enabled by removing the &lt;exclude name=&quot;...&quot;/&gt; that was keeping it out rather than by adding a second reference to it.
  • org.openrewrite.java.pmd.ModernizePmd
    • Modernize a PMD ruleset
    • Bring a PMD ruleset XML file up to date with current PMD, by updating the &lt;rule&gt; references and &lt;exclude&gt; elements to name each rule as PMD knows it today. This runs both the PMD 6 to 7 migration, which replaces the rules PMD 7 deleted and drops the ones deleted without a successor, and the PMD 7 rule renames, which adopt the current name of each rule PMD renamed within the PMD 7 line. Rules whose replacement requires a judgement call, either because PMD split one rule across several successors or because the successor reports something different, are left alone. The result requires PMD 7.27.0 or later; an earlier PMD 7 fails to load a name that its version does not know yet.
  • org.openrewrite.java.pmd.Pmd6to7Migration
    • Migrate a PMD 6 ruleset to PMD 7
    • PMD 7 deleted the rules that had been deprecated throughout the PMD 6 line, and PMD refuses to load a ruleset that references a rule it does not know. Update the &lt;rule&gt; references and &lt;exclude&gt; elements in PMD ruleset XML files to name each deleted rule's successor, and drop the references to rules that were deleted without one. Rules whose behaviour PMD split across several successors, such as VariableNamingConventions and the primitive wrapper *Instantiation rules, are left alone because picking a single replacement for them requires a judgement call.
  • org.openrewrite.java.pmd.Pmd7RuleRenames
    • Rename PMD rules that were renamed within the PMD 7 line
    • PMD renamed a number of rules during the PMD 7 line, keeping the old name as a deprecated alias that PMD still loads but warns about. Update the &lt;rule&gt; references and &lt;exclude&gt; elements in PMD ruleset XML files to name each rule's current name, so the ruleset stops emitting deprecation warnings and keeps loading once PMD 8 drops the aliases. Only true renames are applied, meaning the cases where PMD kept the old name as an alias pointing at the new one. Rules PMD deprecated in favour of a different rule, such as AvoidCatchingNPE in favour of the configurable AvoidCatchingGenericException, GenericsNaming in favour of TypeParameterNamingConventions, UnnecessaryLocalBeforeReturn in favour of VariableCanBeInlined, UseObjectForClearerAPI in favour of ExcessiveParameterList, and CheckSkipResult, AvoidLosingExceptionInformation and UselessOperationOnImmutable in favour of UnusedReturnValue, are left alone, because the successor reports different things and adopting it is a judgement call rather than a rename. The new names require PMD 7.27.0 or later; a ruleset for an earlier PMD 7 fails to load a name that its version does not know yet.
  • org.openrewrite.java.pmd.RemovePmdRule
    • Remove a PMD rule from a ruleset
    • Removes both &lt;rule ref=&quot;...&quot;/&gt; references to a rule and &lt;exclude name=&quot;...&quot;/&gt; elements naming it from PMD ruleset XML files. Intended for rules that PMD deleted without offering a replacement, since PMD fails to load a ruleset that references a rule it does not know.
  • org.openrewrite.java.pmd.ReplacePmdRule
    • Replace a PMD rule in a ruleset
    • Updates &lt;rule ref=&quot;...&quot;/&gt; references and &lt;exclude name=&quot;...&quot;/&gt; elements in PMD ruleset XML files to name a rule's replacement. An &lt;exclude&gt; is only renamed when the replacement lives in the same ruleset file, because an exclusion can only name a rule from the ruleset its enclosing &lt;rule&gt; refers to; when the replacement moved to another ruleset file the exclusion no longer names a rule PMD knows, so it is removed instead.

rewrite-prethink​

License: Moderne Source Available License

5 recipes

  • org.openrewrite.prethink.ExportContext
    • Export context files
    • Export DataTables to CSV files in .moderne/context/ along with a markdown description file. The markdown file describes the context and includes schema information for each data table.
  • org.openrewrite.prethink.UpdateAgentConfig
    • Update agent configuration files
    • Update coding agent configuration files (CLAUDE.md, .cursorrules, etc.) to include references to Moderne Prethink context files in .moderne/context/.
  • org.openrewrite.prethink.UpdateGitignore
    • Update .gitignore for Prethink context
    • Updates .gitignore to allow committing the .moderne/context/ directory while ignoring other files in .moderne/. Only modifies .gitignore when context files exist in .moderne/context/. Transforms .moderne/ into .moderne/* with an exception for !.moderne/context/.
  • org.openrewrite.prethink.UpdatePrethinkContext
    • Update Prethink context
    • Generate FINOS CALM architecture diagram and update agent configuration files. This recipe expects CALM-related data tables (ServiceEndpoints, DatabaseConnections, ExternalServiceCalls, MessagingConnections, etc.) to be populated by other recipes in a composite.
  • org.openrewrite.prethink.calm.GenerateCalmArchitecture
    • Generate CALM architecture
    • Generate a FINOS CALM (Common Architecture Language Model) JSON file from discovered service endpoints, database connections, external service calls, and messaging connections. This recipe is not meant to be run on its own. It only reads data tables that other Prethink discovery recipes populate first, so it produces nothing useful in isolation. Run it as part of a composite such as org.openrewrite.prethink.UpdatePrethinkContext.

rewrite-quarkus​

License: Apache License Version 2.0

24 recipes

rewrite-reactive-streams​

License: Moderne Proprietary License

25 recipes

rewrite-rewrite​

License: Moderne Source Available License

43 recipes

rewrite-spring​

License: Moderne Source Available License

341 recipes

rewrite-spring-to-quarkus​

License: Moderne Source Available License

67 recipes

rewrite-sql​

License: Moderne Proprietary License

34 recipes

  • org.openrewrite.sql.ChangeFunctionName
    • Change a SQL function name
    • When migrating between dialects, often one name can be substituted for another. For example, Oracle's NVL function can be replaced with Postgres COALESCE.
  • org.openrewrite.sql.ConvertDataType
    • Convert SQL data type
    • When migrating between SQL dialects, data types often need to be converted. For example, Oracle's VARCHAR2 can be replaced with Postgres VARCHAR, or NUMBER with NUMERIC.
  • org.openrewrite.sql.ConvertOracleDataTypesToPostgres
    • Convert Oracle data types to PostgreSQL
    • Replaces Oracle-specific data types with PostgreSQL equivalents.
  • org.openrewrite.sql.ConvertOracleFunctionsToPostgres
    • Convert Oracle functions to PostgreSQL
    • Replaces Oracle-specific functions with PostgreSQL equivalents.
  • org.openrewrite.sql.ConvertSqlServerDataTypesToPostgres
    • Convert SQL Server data types to PostgreSQL
    • Replaces SQL Server-specific data types with PostgreSQL equivalents.
  • org.openrewrite.sql.ConvertSqlServerFunctionsToPostgres
    • Convert SQL Server functions to PostgreSQL
    • Replaces SQL Server-specific functions with PostgreSQL equivalents.
  • org.openrewrite.sql.FindSql
    • Find SQL in code and resource files
    • Find SQL in code (e.g. in string literals) and in resources like those ending with .sql.
  • org.openrewrite.sql.FormatSql
    • Format SQL in string text blocks
    • Checks whether a text block may contain SQL, and if so, formats the text accordingly.
  • org.openrewrite.sql.MigrateOracleToPostgres
    • Migrate Oracle SQL to PostgreSQL
    • Converts Oracle-specific SQL syntax and functions to PostgreSQL equivalents.
  • org.openrewrite.sql.MigrateSqlServerToPostgres
    • Migrate SQL Server to PostgreSQL
    • Converts Microsoft SQL Server-specific SQL syntax and functions to PostgreSQL equivalents.
  • org.openrewrite.sql.antipattern.FindCartesianJoin
    • Find cartesian joins
    • Joins that lack a real linking predicate multiply row counts instead of matching related rows: an ON condition comparing a column to itself is always true, and comma-separated tables with no WHERE predicate relating them pair every row with every row. Explicit CROSS JOIN and NATURAL joins are treated as intentional and are not flagged.
  • org.openrewrite.sql.antipattern.FindConstantPredicate
    • Find constant predicates that are always true or always false
    • A comparison whose operands are both constant, such as 1 = 1 or 1 = 0, evaluates the same for every row regardless of the data. Combined with OR an always-true constant makes the whole condition always true, so every row matches and the other filters are ignored; an always-false constant used as a filter can never be satisfied, so the query returns nothing. An always-true constant on its own or joined with AND, a common query-builder idiom, is not flagged.
  • org.openrewrite.sql.antipattern.FindCorrelatedAggregateSubquery
    • Find correlated aggregate subqueries in WHERE
    • A scalar subquery that computes an aggregate like MAX while referencing the outer query runs once per outer row on engines that cannot decorrelate it. A window function or a join to a pre-aggregated derived table computes every group in a single pass. Uncorrelated aggregate subqueries and EXISTS or IN subqueries are not flagged.
  • org.openrewrite.sql.antipattern.FindCountAsExistenceCheck
    • Find COUNT subqueries used as existence checks
    • A scalar COUNT subquery compared to 0 or 1 tallies every matching row even though the outcome is decided by the first one. EXISTS or NOT EXISTS lets the engine stop as soon as a match is found. Comparisons against other values, such as &gt; 5, express a genuine cardinality requirement and are not flagged.
  • org.openrewrite.sql.antipattern.FindDistinctWithJoin
    • Find DISTINCT masking join fan-out
    • DISTINCT paired with a JOIN frequently compensates for row multiplication that a correct join condition or an EXISTS test would avoid, and DISTINCT alongside GROUP BY is redundant because grouping already collapses duplicate rows. A DISTINCT on a single-table query without GROUP BY is not flagged.
  • org.openrewrite.sql.antipattern.FindDmlWithoutWhere
    • Find UPDATE and DELETE statements without a WHERE clause
    • An UPDATE or DELETE with no WHERE clause touches every row in the table, holding locks for the duration, flooding replication, and risking unintended data loss if the missing predicate was an oversight.
  • org.openrewrite.sql.antipattern.FindHavingWithoutAggregate
    • Find HAVING conditions that use no aggregate
    • A HAVING condition that references no aggregate forces the database to build every group before throwing unwanted ones away. The same condition in WHERE filters rows before grouping, doing strictly less work.
  • org.openrewrite.sql.antipattern.FindInsertWithoutColumns
    • Find INSERT ... VALUES statements that omit the column list
    • An INSERT ... VALUES with no column list binds each value to a column by position, so adding, dropping, or reordering a column silently shifts values into the wrong columns or breaks the statement; naming the target columns keeps it correct across schema changes. INSERT ... SELECT is left alone, since its projection makes the column correspondence explicit.
  • org.openrewrite.sql.antipattern.FindLeadingWildcardLike
    • Find LIKE patterns starting with a wildcard
    • A LIKE pattern whose first character is % or _ gives the database no prefix to seek in a B-tree index, so every row must be inspected. When a prefix search is not possible, a trigram or full-text index can serve the query instead. Parameter placeholders and patterns with only trailing wildcards are not flagged.
  • org.openrewrite.sql.antipattern.FindLimitWithoutOrderBy
    • Find row limiters without an ORDER BY
    • A LIMIT, OFFSET, FETCH, or TOP clause selects a subset of rows, but without an ORDER BY the engine is free to return any rows in any order, so the result is arbitrary and can differ from one execution to the next. Queries that can only ever produce a single row, such as a bare aggregate with no GROUP BY, and limiters inside an EXISTS subquery, where order does not matter, are not flagged.
  • org.openrewrite.sql.antipattern.FindNonSargablePredicate
    • Find non-sargable predicates
    • A comparison that wraps a column in a function, CAST, or arithmetic must evaluate the expression for every row, so an index on the bare column cannot be used for a range scan. Keeping the column alone on one side, e.g. amount &gt; 100 - 1 rather than amount + 1 &gt; 100, keeps the predicate index-eligible.
  • org.openrewrite.sql.antipattern.FindNotInSubquery
    • Find NOT IN with a subquery
    • When the subquery can return a NULL, NOT IN evaluates to unknown for every row and the outer query silently returns nothing. Many planners also fail to rewrite NOT IN as an efficient anti-join. NOT EXISTS avoids both problems. NOT IN over a literal list is not flagged.
  • org.openrewrite.sql.antipattern.FindOffsetPagination
    • Find OFFSET-based pagination
    • OFFSET n reads and throws away n rows before returning any, so each later page costs linearly more than the one before it. Parameterized offsets and large literal offsets are flagged; keyset pagination (WHERE key &gt; last-seen ORDER BY key) reads only the requested page. Small literal offsets are not flagged.
  • org.openrewrite.sql.antipattern.FindOptionalParameterOr
    • Find optional filters written as OR parameter IS NULL
    • The col = ? OR ? IS NULL pattern turns a filter on and off at runtime, so the planner must settle on one generic plan that works for every parameter combination instead of an index-driven plan for the filtered case. An IS NULL test on a column inside an OR is ordinary SQL and is not flagged.
  • org.openrewrite.sql.antipattern.FindOrderByRandom
    • Find ORDER BY on a random function
    • Sorting by RAND(), RANDOM(), NEWID(), or DBMS_RANDOM computes a random value for every row and sorts the entire table just to keep a few rows. Sample by a key range or use the dialect's table sampling instead.
  • org.openrewrite.sql.antipattern.FindOversizedInList
    • Find oversized IN lists
    • A very long IN list is parsed and planned on every execution, tends to pollute the statement cache, and some databases hard-cap the number of elements it may contain. Loading the values into a temporary table and joining against it scales far better. IN with a subquery is not flagged.
  • org.openrewrite.sql.antipattern.FindScalarSubqueryInSelect
    • Find scalar subqueries in the SELECT list
    • A subquery used as an expression in the SELECT list may execute once per result row, turning a single scan into N+1 queries. A JOIN (or LATERAL join) produces the same values in one pass. Subqueries in WHERE, FROM, or JOIN conditions are not flagged.
  • org.openrewrite.sql.antipattern.FindSelectStar
    • Find SELECT * queries
    • Wildcard projections fetch columns the code does not use, defeat covering indexes, and change behavior when the schema changes. SELECT * under EXISTS (...) or inside aggregate functions like COUNT(*) is not flagged because no columns are materialized there.
  • org.openrewrite.sql.antipattern.FindUnionInsteadOfUnionAll
    • Find UNION where UNION ALL may suffice
    • Plain UNION de-duplicates the combined rows, forcing a sort or hash over the entire result even when the branches cannot overlap. UNION ALL skips that work. UNION inside a WITH item is not flagged because recursive CTEs rely on plain UNION semantics to terminate.
  • org.openrewrite.sql.antipattern.RemoveOrderByInSubquery
    • Remove redundant ORDER BY from subqueries
    • An ORDER BY inside a subquery or CTE without a LIMIT, OFFSET, or FETCH does not affect the rows the outer query returns, so the database either discards the sort or pays for ordering that nothing observes. Remove the clause, leaving the rest of the statement untouched. Sort in the outermost query if a specific order is required.
  • org.openrewrite.sql.antipattern.ReplaceNullComparisonWithIsNull
    • Replace = NULL and &lt;&gt; NULL with IS NULL and IS NOT NULL
    • Under three-valued logic a comparison with NULL evaluates to UNKNOWN rather than true, so col = NULL and col &lt;&gt; NULL match no rows. Rewrite them to the intended col IS NULL and col IS NOT NULL, changing only the compared operator so the rest of the statement is left untouched.
  • org.openrewrite.sql.antipattern.SqlAntiPatterns
    • Find and fix SQL performance anti-patterns
    • Analyzes SQL found in code and resource files for statically detectable performance anti-patterns such as SELECT *, COUNT(*) used as an existence check, scalar subqueries in the SELECT list, non-sargable predicates, and missing join conditions. Every occurrence is reported to the SqlAntiPatterns data table with a severity and suggested remediation, then fixed in place where a safe rewrite exists or marked in source otherwise.
  • org.openrewrite.sql.search.FindFunction
    • Find SQL function
    • Find SQL functions by name.
  • org.openrewrite.sql.search.FindStoredProcedureCall
    • Find stored procedure calls
    • Find stored procedures invoked from SQL via EXEC, EXECUTE, or CALL. Useful for taking inventory of the stored procedures a codebase depends on when planning a database migration.

rewrite-static-analysis​

License: Moderne Source Available License

205 recipes

  • org.openrewrite.recipe.rewrite-static-analysis.InlineDeprecatedMethods
    • Inline deprecated delegating methods
    • Automatically generated recipes to inline deprecated method calls that delegate to other methods in the same class.
  • org.openrewrite.staticanalysis.AbstractClassPublicConstructor
    • Constructors of an abstract class should not be declared public
    • Constructors of abstract classes can only be called in constructors of their subclasses. Therefore the visibility of public constructors are reduced to protected. Declaring them public is misleading since it implies they could be invoked directly, which is never possible.
  • org.openrewrite.staticanalysis.AddSerialAnnotationToSerialVersionUID
    • Add @Serial annotation to serialVersionUID
    • Annotate any serialVersionUID fields with @Serial to indicate it's part of the serialization mechanism.
  • org.openrewrite.staticanalysis.AddSerialVersionUidToSerializable
    • Add serialVersionUID to a Serializable class when missing
    • A serialVersionUID field is strongly recommended in all Serializable classes. If this is not defined on a Serializable class, the compiler will generate this value. If a change is later made to the class, the generated value will change and attempts to deserialize the class will fail. Explicitly declaring this field gives you control over binary compatibility across versions.
  • org.openrewrite.staticanalysis.AllBranchesIdentical
    • All branches in a conditional should not have the same implementation
    • When every branch of an if/else chain executes the same code, the condition serves no purpose and the code block can be used directly.
  • org.openrewrite.staticanalysis.AnnotateNullableMethods
    • Annotate methods which may return null with @Nullable
    • Add @Nullable to non-private methods that may return null. By default org.jspecify.annotations.Nullable is used, but through the nullableAnnotationClass option a custom annotation can be provided. Both @Target(TYPE_USE) and declaration annotations (e.g. javax.annotation.CheckForNull) are supported. Methods that already carry a known nullable annotation (matched by simple name) are skipped to avoid duplication. This recipe scans for methods that do not already have a @Nullable annotation and checks their return statements for potential null values. It also identifies known methods from standard libraries that may return null, such as methods from Map, Queue, Deque, NavigableSet, and Spliterator. The return of streams, or lambdas are not taken into account.
  • org.openrewrite.staticanalysis.AnnotateNullableParameters
    • Annotate null-checked method parameters with @Nullable
    • Add @Nullable to parameters of public methods that are explicitly checked for null. By default org.jspecify.annotations.Nullable is used, but through the nullableAnnotationClass option a custom annotation can be provided. Both @Target(TYPE_USE) and declaration annotations (e.g. javax.annotation.CheckForNull) are supported. Parameters that already carry a known nullable annotation are skipped to avoid duplication. This recipe scans for methods that do not already have parameters annotated with a nullable annotation and checks their usages for potential null checks. Additional null-checking methods can be specified via the additionalNullCheckingMethods option.
  • org.openrewrite.staticanalysis.AnnotateRequiredParameters
    • Annotate required method parameters with @NonNull
    • Add @NonNull to parameters of public methods that are explicitly checked for null and throw an exception if null. By default org.jspecify.annotations.NonNull is used, but through the nonNullAnnotationClass option a custom annotation can be provided. When providing a custom nonNullAnnotationClass that annotation should be meta annotated with @Target(TYPE_USE). This recipe scans for methods that do not already have parameters annotated with @NonNull annotation and checks for null validation patterns that throw exceptions, such as if (param == null) throw new IllegalArgumentException().
  • org.openrewrite.staticanalysis.AtomicPrimitiveEqualsUsesGet
    • Atomic Boolean, Integer, and Long equality checks compare their values
    • AtomicBoolean#equals(Object), AtomicInteger#equals(Object) and AtomicLong#equals(Object) are only equal to their instance. This recipe converts a.equals(b) to a.get() == b.get(). These atomic classes do not override equals from Object, so calling it compares object identity rather than the wrapped value, which is almost never the intended behavior.
  • org.openrewrite.staticanalysis.AvoidBoxedBooleanExpressions
    • Avoid boxed boolean expressions
    • Under certain conditions the java.lang.Boolean type is used as an expression, and it may throw a NullPointerException if the value is null. Using Boolean.TRUE.equals(...) guards against unboxing a null reference in control flow positions like if conditions and ternary operators.
  • org.openrewrite.staticanalysis.BigDecimalDoubleConstructorRecipe
    • new BigDecimal(double) should not be used
    • Use of new BigDecimal(double) constructor can lead to loss of precision. Use BigDecimal.valueOf(double) instead. For example writing new BigDecimal(0.1) does not create a BigDecimal which is exactly equal to 0.1, but it is equal to 0.1000000000000000055511151231257827021181583404541015625. This is because 0.1 cannot be represented exactly as a double (or, for that matter, as a binary fraction of any finite length). BigDecimal.valueOf avoids this by converting through a string representation, preserving the value you actually intended.
  • org.openrewrite.staticanalysis.BigDecimalRoundingConstantsToEnums
    • BigDecimal rounding constants to RoundingMode enums
    • Convert BigDecimal rounding constants to the equivalent RoundingMode enum. The integer-based rounding constants on BigDecimal are deprecated and lack type safety; the RoundingMode enum makes the rounding behavior self-documenting and prevents invalid values.
  • org.openrewrite.staticanalysis.BooleanChecksNotInverted
    • Boolean checks should not be inverted
    • Ensures that boolean checks are not unnecessarily inverted. Also fixes double negative boolean expressions. Negating a comparison and then inverting it adds cognitive overhead; using the direct operator (e.g., &gt;= instead of !(... &lt; ...)) is clearer and easier to reason about.
  • org.openrewrite.staticanalysis.BufferedWriterCreationRecipes
    • Modernize BufferedWriter creation & prevent file descriptor leaks
    • The code new BufferedWriter(new FileWriter(f)) creates a BufferedWriter that does not close the underlying FileWriter when it is closed. This can lead to file descriptor leaks as per CWE-755. Use Files.newBufferedWriter to create a BufferedWriter that closes the underlying file descriptor when it is closed.
  • org.openrewrite.staticanalysis.BufferedWriterCreationRecipes$BufferedWriterFromNewFileWriterWithFileAndBooleanArgumentsRecipe
    • Convert new BufferedWriter(new FileWriter(File, boolean)) to Files.newBufferedWriter(Path, StandardOpenOption)
    • Convert new BufferedWriter(new FileWriter(f, b)) to Files.newBufferedWriter(f.toPath(), b ? StandardOpenOption.APPEND : StandardOpenOption.CREATE).
  • org.openrewrite.staticanalysis.BufferedWriterCreationRecipes$BufferedWriterFromNewFileWriterWithFileArgumentRecipe
    • Convert new BufferedWriter(new FileWriter(File)) to Files.newBufferedWriter(Path)
    • Convert new BufferedWriter(new FileWriter(f)) to Files.newBufferedWriter(f.toPath()).
  • org.openrewrite.staticanalysis.BufferedWriterCreationRecipes$BufferedWriterFromNewFileWriterWithStringAndBooleanArgumentsRecipe
    • Convert new BufferedWriter(new FileWriter(String, boolean)) to Files.newBufferedWriter(Path, StandardOpenOption)
    • Convert new BufferedWriter(new FileWriter(s, b)) to Files.newBufferedWriter(new java.io.File(s).toPath(), b ? StandardOpenOption.APPEND : StandardOpenOption.CREATE).
  • org.openrewrite.staticanalysis.BufferedWriterCreationRecipes$BufferedWriterFromNewFileWriterWithStringArgumentRecipe
    • Convert new BufferedWriter(new FileWriter(String)) to Files.newBufferedWriter(Path)
    • Convert new BufferedWriter(new FileWriter(s)) to Files.newBufferedWriter(new java.io.File(s).toPath()).
  • org.openrewrite.staticanalysis.CaseInsensitiveComparisonsDoNotChangeCase
    • CaseInsensitive comparisons do not alter case
    • Remove String#toLowerCase() or String#toUpperCase() from String#equalsIgnoreCase(..) comparisons. Changing case before a case-insensitive comparison is redundant and allocates unnecessary intermediate String objects.
  • org.openrewrite.staticanalysis.CatchClauseOnlyRethrows
    • Catch clause should do more than just rethrow
    • A catch clause that only rethrows the caught exception is unnecessary. Letting the exception bubble up as normal achieves the same result with less code. Such catch blocks add visual noise and indentation without changing program behavior.
  • org.openrewrite.staticanalysis.ChainStringBuilderAppendCalls
    • Chain StringBuilder.append() calls
    • String concatenation within calls to StringBuilder.append() causes unnecessary memory allocation. Except for concatenations of String literals, which are joined together at compile time. Replaces inefficient concatenations with chained calls to StringBuilder.append(). Using + inside append() defeats the purpose of the StringBuilder, since the concatenation creates a temporary String before appending.
  • org.openrewrite.staticanalysis.CodeCleanup
    • Code cleanup
    • Automatically cleanup code, e.g. remove unnecessary parentheses, simplify expressions.
  • org.openrewrite.staticanalysis.CollapsibleIfStatements
    • Mergeable "if" statements should be combined
    • When an if statement body contains only another if with no else, the two conditions can be combined with &amp;&amp;. Merging the conditions reduces nesting and makes the code easier to read.
  • org.openrewrite.staticanalysis.CollectionToArrayShouldHaveProperType
    • 'Collection.toArray()' should be passed an array of the proper type
    • Using Collection.toArray() without parameters returns an Object[], which requires casting. It is more efficient and clearer to use Collection.toArray(new T[0]) instead. The parameterless form can cause a ClassCastException at runtime when the returned Object[] is cast to a more specific array type.
  • org.openrewrite.staticanalysis.CombineSemanticallyEqualCatchBlocks
    • Combine semantically equal catch blocks
    • Combine catches in a try that contain semantically equivalent blocks. No change will be made when a caught exception exists if combining catches may change application behavior or type attribution is missing. Merging duplicate catch bodies into multi-catch blocks reduces repetition and makes the exception handling strategy easier to follow.
  • org.openrewrite.staticanalysis.CommonDeclarationSiteTypeVariances
    • Properly use declaration-site type variance for well-known types
    • When using a method parameter like Function&lt;IN, OUT&gt;, it should rather be Function&lt;? super IN, ? extends OUT&gt;. This recipe checks for method parameters of well-known types.
  • org.openrewrite.staticanalysis.CommonStaticAnalysis
    • Common static analysis issues
    • Resolve common static analysis issues (also known as SAST issues).
  • org.openrewrite.staticanalysis.CompareEnumsWithEqualityOperator
    • Enum values should be compared with "=="
    • Replaces Enum equals(java.lang.Object) with Enum == java.lang.Object. An !Enum equals(java.lang.Object) will change to !=. Using == for enum comparison is null-safe, catches type mismatches at compile time, and is idiomatic since each enum constant is guaranteed to be a singleton.
  • org.openrewrite.staticanalysis.ControlFlowIndentation
    • Control flow statement indentation
    • Program flow control statements like if, while, and for can omit curly braces when they apply to only a single statement. This recipe ensures that any statements which follow that statement are correctly indented to show they are not part of the flow control statement. Misleading indentation can give the false impression that a line executes conditionally when it actually runs unconditionally, which is a common source of logic errors.
  • org.openrewrite.staticanalysis.CovariantEquals
    • Covariant equals
    • Checks that classes and records which define a covariant equals() method also override method equals(Object). Covariant equals() means a method that is similar to equals(Object), but with a covariant parameter type (any subtype of Object). Without a proper equals(Object) override, collections and other framework code that rely on the standard signature will silently use Object.equals, leading to incorrect behavior.
  • org.openrewrite.staticanalysis.DeclarationSiteTypeVariance
    • Properly use declaration-site type variance
    • Currently, Java requires use-site type variance, so if someone has Function&lt;IN, OUT&gt; method parameter, it should rather be Function&lt;? super IN, ? extends OUT&gt;. Unfortunately, it is not easy to notice that ? super and ? extends is missing, so this recipe adds it where that would improve the situation.
  • org.openrewrite.staticanalysis.DefaultComesLast
    • Default comes last
    • Ensure the default case comes last after all the cases in a switch statement. Placing default at the end follows a widely expected convention, making it easy to find the fallback behavior at a glance.
  • org.openrewrite.staticanalysis.EmptyBlock
    • Remove empty blocks
    • Remove empty blocks that effectively do nothing. Empty blocks are ambiguous -- they may indicate incomplete implementation or accidentally deleted code -- and removing them makes the intent of the surrounding code explicit.
  • org.openrewrite.staticanalysis.EqualsAvoidsNull
    • Equals avoids null
    • Checks that any combination of String literals is on the left side of an equals() comparison. Also checks for String literals assigned to some field (such as someString.equals(anotherString = &quot;text&quot;)). And removes redundant null checks in conjunction with equals comparisons. Placing the literal on the left side prevents NullPointerExceptions, since a literal can never be null and its equals method handles null arguments safely.
  • org.openrewrite.staticanalysis.EqualsToContentEquals
    • Use String.contentEquals(CharSequence) instead of String.equals(CharSequence.toString())
    • Use String.contentEquals(CharSequence) instead of String.equals(CharSequence.toString()).
  • org.openrewrite.staticanalysis.ExplicitCharsetOnStringGetBytes
    • Set charset encoding explicitly when calling String#getBytes
    • This makes the behavior of the code platform neutral. It will not override any existing explicit encodings, even if they don't match the default encoding option. Relying on the platform default charset can produce different results across environments, leading to subtle data corruption bugs.
  • org.openrewrite.staticanalysis.ExplicitInitialization
    • Explicit initialization
    • Checks if any class or object member is explicitly initialized to default for its type value: - null for object references - zero for numeric types and char - and false for boolean Removes explicit initializations where they aren't necessary. Since the JVM already guarantees these defaults, restating them adds visual noise and can obscure fields that are intentionally initialized to non-default values.
  • org.openrewrite.staticanalysis.ExplicitLambdaArgumentTypes
    • Use explicit types on lambda arguments
    • Adds explicit types on lambda arguments, which are otherwise optional. This can make the code clearer and easier to read. This does not add explicit types on arguments when the lambda has one or two parameters and does not have a block body, as things are considered more readable in those cases. For example, stream.map((a, b) -&gt; a.length); will not have explicit types added.
  • org.openrewrite.staticanalysis.ExplicitThis
    • Use explicit this.field and this.method()
    • Add explicit 'this.' prefix to field and method access.
  • org.openrewrite.staticanalysis.ExternalizableHasNoArgsConstructor
    • Externalizable classes have no-arguments constructor
    • Externalizable classes handle both serialization and deserialization and must have a no-args constructor for the deserialization process. Without a public no-argument constructor, the JVM cannot instantiate the object during deserialization and will throw an InvalidClassException at runtime.
  • org.openrewrite.staticanalysis.FallThrough
    • Fall through
    • Checks for fall-through in switch statements, adding break statements in locations where a case contains Java code but does not have a break, return, throw, or continue statement. Unintentional fall-through is a common source of bugs, as execution silently continues into the next case branch.
  • org.openrewrite.staticanalysis.FinalClass
    • Finalize classes with private constructors
    • Adds the final modifier to classes that expose no public or package-private constructors. If a class cannot be instantiated from the outside, marking it final communicates that it was not designed for inheritance and prevents accidental subclassing.
  • org.openrewrite.staticanalysis.FinalizeLocalVariables
    • Finalize local variables
    • Adds the final modifier keyword to local variables which are not reassigned.
  • org.openrewrite.staticanalysis.FinalizeMethodArguments
    • Finalize method arguments
    • Adds the final modifier keyword to method parameters.
  • org.openrewrite.staticanalysis.FinalizePrivateFields
    • Finalize private fields
    • Adds the final modifier keyword to private instance variables which are not reassigned.
  • org.openrewrite.staticanalysis.FindIgnoredCheckReturnValue
    • Find ignored results of @CheckReturnValue methods
    • Marks invocations whose result is discarded even though the method is annotated with @CheckReturnValue, either directly or through its enclosing class or package. Any annotation named CheckReturnValue is recognized, and @CanIgnoreReturnValue opts a method or class back out. Ignoring such a result is usually a bug, such as calling a method on an immutable object without using the returned copy. Calls expected to throw, Mockito stubbing and verification, calls on the current instance in custom AssertJ assertion constructors, and code under @SuppressWarnings(&quot;CheckReturnValue&quot;) are not marked.
  • org.openrewrite.staticanalysis.FindMainWithThrowsClause
    • Find main methods with a throws clause
    • Marks JVM entry-point main methods (public static void main(String[]) or the varargs equivalent) that declare a throws clause. Uncaught exceptions from main propagate to the JVM's default handler, which just prints the stack trace and returns exit code 1. Handle exceptions explicitly and exit with a meaningful code.
  • org.openrewrite.staticanalysis.FindMissingJavadocOnPublicMethods
    • Find public methods missing Javadoc
    • Locates public method declarations that are not documented with a Javadoc comment, marks them with a search result, and records them in a data table.
  • org.openrewrite.staticanalysis.FindNewExceptionWithoutCause
    • Find new exceptions thrown without the caught exception
    • Finds catch blocks that throw a newly created exception without referencing the caught exception, which discards the original exception's stack trace and message. Taint tracking over the local variables of the catch block establishes whether the caught exception—or any value derived from it—reaches the thrown exception, so indirect references through local variables, helper calls and string concatenation are not falsely reported. This mirrors PMD's PreserveStackTrace rule.
  • org.openrewrite.staticanalysis.FindSystemAndRuntimeExitCalls
    • Find JVM exit calls
    • Marks calls to System.exit(int), Runtime.exit(int), and Runtime.halt(int). Terminating the JVM from library or application code is rarely correct: it bypasses the normal shutdown flow, prevents finally blocks from running in other threads, and can leave file, socket, and database resources in an inconsistent state. Runtime.halt is particularly dangerous because it also skips shutdown hooks.
  • org.openrewrite.staticanalysis.FindThreadGroupUsages
    • Find ThreadGroup usages
    • Marks uses of java.lang.ThreadGroup. ThreadGroup was originally intended to help with thread management but its API has serious design flaws (most methods are either deprecated or unsafe) and it has been superseded by java.util.concurrent.ExecutorService. Sites flagged include new ThreadGroup(...) constructor calls, calls to Thread.getThreadGroup(), and method invocations on ThreadGroup receivers.
  • org.openrewrite.staticanalysis.FindWaitWithMultipleLocksHeld
    • Find Object.wait() calls made while holding multiple monitors
    • Finds zero-argument Object.wait() invocations whose enclosing method holds two or more monitors — either through nested synchronized (...) blocks, or a synchronized method combined with a nested synchronized block. wait() releases only the monitor of its receiver, so other held monitors continue to block their waiters and can deadlock. Timed waits (wait(long), wait(long, int)) are intentionally excluded — sonar-java's S3046 does the same, since timed waits are self-releasing and less likely to cause the failure mode.
  • org.openrewrite.staticanalysis.FixStringFormatExpressions
    • Fix String#format and String#formatted expressions
    • Fix String#format and String#formatted expressions by replacing \n newline characters with %n and removing any unused arguments. Note this recipe is scoped to only transform format expressions which do not specify the argument index. Using %n ensures the correct platform-specific line separator, and removing unused arguments eliminates dead code that may mask a mismatch between the format string and its parameters.
  • org.openrewrite.staticanalysis.ForLoopControlVariablePostfixOperators
    • for loop counters should use postfix operators
    • Replace for loop control variables using pre-increment (++i) or pre-decrement (--i) operators with their post-increment (i++) or post-decrement (i++) notation equivalents.
  • org.openrewrite.staticanalysis.ForLoopIncrementInUpdate
    • for loop counters incremented in update
    • The increment should be moved to the loop's increment clause if possible. Placing the counter update in the loop body rather than the update clause obscures the loop's control flow and makes it harder to reason about termination.
  • org.openrewrite.staticanalysis.HiddenField
    • Hidden field
    • Refactor local variables or parameters which shadow a field defined in the same class. Shadowing a field with a local variable of the same name makes it easy to accidentally reference the wrong one, leading to confusing bugs.
  • org.openrewrite.staticanalysis.HideUtilityClassConstructor
    • Hide utility class constructor
    • Ensures utility classes (classes containing only static methods or fields in their API) do not have a public constructor. Instantiating a utility class is almost certainly a mistake, and a private constructor makes that intent clear while preventing misuse.
  • org.openrewrite.staticanalysis.IndexOfChecksShouldUseAStartPosition
    • Use indexOf(String, int)
    • Replaces indexOf(String) in binary operations if the compared value is an int and not less than 1. Using the two-argument indexOf(String, int) form with a start position avoids redundantly scanning the beginning of the string when you already know the match must occur after a certain index.
  • org.openrewrite.staticanalysis.IndexOfReplaceableByContains
    • indexOf() replaceable by contains()
    • Checking if a value is included in a String or List using indexOf(value)&gt;-1 or indexOf(value)&gt;=0 can be replaced with contains(value). Using contains() expresses the intent more directly and avoids the mental overhead of interpreting index comparisons.
  • org.openrewrite.staticanalysis.IndexOfShouldNotCompareGreaterThanZero
    • indexOf should not compare greater than zero
    • Replaces String#indexOf(String) &gt; 0 and List#indexOf(Object) &gt; 0 with &gt;=1. Checking indexOf against &gt;0 ignores the first element, whereas &gt;-1 is inclusive of the first element. For clarity, &gt;=1 is used, because &gt;0 and &gt;=1 are semantically equal. Using &gt;0 may appear to be a mistake with the intent of including all elements. If the intent is to check whether a value in included in a String or List, the String#contains(String) or List#contains(Object) methods may be better options altogether.
  • org.openrewrite.staticanalysis.InlineVariable
    • Inline variable
    • Inline variables when they are immediately used to return or throw. Supports both variable declarations and assignments to local variables. A variable that is declared only to be returned or thrown on the very next line adds an unnecessary level of indirection without improving readability.
  • org.openrewrite.staticanalysis.InstanceOfPatternMatch
    • Changes code to use Java 17's instanceof pattern matching
    • Adds pattern variables to instanceof expressions wherever the same (side effect free) expression is referenced in a corresponding type cast expression within the flow scope of the instanceof. Currently, this recipe supports if statements and ternary operator expressions. Pattern matching for instanceof collapses the type check, cast, and variable declaration into a single expression, reducing boilerplate and eliminating the risk of an incorrect cast.
  • org.openrewrite.staticanalysis.InterruptedExceptionHandling
    • Restore interrupted state in catch blocks
    • When InterruptedException is caught, Thread.currentThread().interrupt() should be called to restore the thread's interrupted state. Failing to do so can suppress the interruption signal and prevent proper thread cancellation.
  • org.openrewrite.staticanalysis.IsEmptyCallOnCollections
    • Use Collection#isEmpty() instead of comparing size()
    • Also check for not isEmpty() when testing for not equal to zero size. Using isEmpty() communicates intent more clearly than comparing size() to zero, and for some collection implementations isEmpty() can be more efficient since size() may require traversal.
  • org.openrewrite.staticanalysis.JavaApiBestPractices
    • Java API best practices
    • Use the Java standard library in a way that is most idiomatic.
  • org.openrewrite.staticanalysis.LambdaBlockToExpression
    • Simplify lambda blocks to expressions
    • Single-line statement lambdas returning a value can be replaced with expression lambdas. Expression-form lambdas are more concise and consistent with a functional programming style, making the code easier to scan.
  • org.openrewrite.staticanalysis.LowercasePackage
    • Rename packages to lowercase
    • By convention all Java package names should contain only lowercase letters, numbers, and dashes. This recipe converts any uppercase letters in package names to be lowercase. Consistent package naming prevents confusion and potential issues on case-insensitive file systems.
  • org.openrewrite.staticanalysis.MaskCreditCardNumbers
    • Mask credit card numbers
    • When encountering string literals which appear to be credit card numbers, mask the last eight digits with the letter 'X'.
  • org.openrewrite.staticanalysis.MemberNameCaseInsensitiveDuplicates
    • Members should not have names differing only by capitalization
    • Looking at the set of methods and fields in a class and all of its parents, no two members should have names that differ only in capitalization. This rule will not report if a method overrides a parent method. Members with near-identical names are easily confused, leading to bugs where the wrong field or method is referenced.
  • org.openrewrite.staticanalysis.MergeIdenticalBranches
    • Branches with identical implementations should be merged
    • When two consecutive branches of an if/else if chain execute the same code, they can be merged by combining their conditions with ||. This removes duplication and makes the intent clearer.
  • org.openrewrite.staticanalysis.MethodNameCasing
    • Standardize method name casing
    • Fixes method names that do not follow standard naming conventions. For example, String getFoo_bar() would be adjusted to String getFooBar() and int DoSomething() would be adjusted to int doSomething(). Following a consistent casing convention for method names improves code readability and helps developers quickly distinguish methods from classes or constants.
  • org.openrewrite.staticanalysis.MinimumSwitchCases
    • switch statements should have at least 3 case clauses
    • switch statements are useful when many code paths branch depending on the value of a single expression. For just one or two code paths, the code will be more readable with if statements. Using switch for trivial branching adds unnecessary syntactic overhead and obscures the simplicity of the logic.
  • org.openrewrite.staticanalysis.MissingOverrideAnnotation
    • Add missing @Override to overriding and implementing methods
    • Adds @Override to methods overriding superclass methods or implementing interface methods. Annotating methods improves readability by showing the author's intent to override. Additionally, when annotated, the compiler will emit an error when a signature of the overridden method does not match the superclass method.
  • org.openrewrite.staticanalysis.ModernizeCollections
    • Modernize collections
    • Replace the legacy synchronized types Hashtable, Vector, Stack, and StringBuffer with their modern unsynchronized counterparts HashMap, ArrayList, Deque/ArrayDeque, and StringBuilder. Each replacement is only applied when data flow analysis can prove the instance is a local variable that never escapes its method, so the synchronization it provided is redundant.
  • org.openrewrite.staticanalysis.ModifierOrder
    • Modifier order
    • Modifiers should be declared in the correct order as recommended by the JLS. Ordering modifiers consistently reduces cognitive load for developers who are accustomed to the standard sequence.
  • org.openrewrite.staticanalysis.MoveConditionsToWhile
    • Convert while (true) with initial if break to loop condition
    • Simplifies while (true) loops where the first statement is an if statement that only contains a break. The condition is inverted and moved to the loop condition for better readability.
  • org.openrewrite.staticanalysis.MultipleVariableDeclarations
    • No multiple variable declarations
    • Places each variable declaration in its own statement and on its own line. Using one variable declaration per line encourages commenting and can increase readability. Multi-variable declarations also make it harder to track individual types and initializers, increasing the risk of subtle errors.
  • org.openrewrite.staticanalysis.NeedBraces
    • Fix missing braces
    • Adds missing braces around code such as single-line if, for, while, and do-while block bodies. Omitting braces can lead to dangling-statement bugs when additional lines are later added to a block without realizing they fall outside the control structure.
  • org.openrewrite.staticanalysis.NestedEnumsAreNotStatic
    • Nested enums are not static
    • Remove static modifier from nested enum types since they are implicitly static. The redundant modifier adds visual noise and may mislead readers into thinking there is a non-static alternative.
  • org.openrewrite.staticanalysis.NewStringBuilderBufferWithCharArgument
    • Change StringBuilder and StringBuffer character constructor argument to String
    • Instantiating a StringBuilder or a StringBuffer with a Character results in the int representation of the character being used for the initial size. This is almost never the developer's intent and silently produces a buffer with an arbitrary capacity instead of the expected initial content.
  • org.openrewrite.staticanalysis.NoDoubleBraceInitialization
    • No double brace initialization
    • Replace List, Map, and Set double brace initialization with an initialization block. Double brace initialization creates an anonymous inner class that holds a hidden reference to the enclosing instance, which can cause memory leaks and serialization issues.
  • org.openrewrite.staticanalysis.NoEmptyCollectionWithRawType
    • Use Collections#emptyList(), emptyMap(), and emptySet()
    • Replaces Collections#EMPTY_... with methods that return generic types. The raw-typed constant fields bypass generics checks, which can hide type mismatches that only surface as ClassCastException at runtime.
  • org.openrewrite.staticanalysis.NoEqualityInForCondition
    • Use comparison rather than equality checks in for conditions
    • Testing for loop termination using an equality operator (== and !=) is dangerous, because it could set up an infinite loop. Using a relational operator instead makes it harder to accidentally write an infinite loop.
  • org.openrewrite.staticanalysis.NoFinalizedLocalVariables
    • Don't use final on local variables
    • Remove the final modifier keyword from local variables regardless of whether they are used within a local class or an anonymous class.
  • org.openrewrite.staticanalysis.NoFinalizer
    • Remove finalize() method
    • Finalizers are deprecated. Use of finalize() can lead to performance issues, deadlocks, hangs, and other undesirable behavior.
  • org.openrewrite.staticanalysis.NoPrimitiveWrappersForToStringOrCompareTo
    • No primitive wrappers for #toString() or #compareTo(..)
    • Primitive wrappers should not be instantiated only for #toString() or #compareTo(..) invocations. Allocating a wrapper object just to call a method that has a static equivalent is wasteful; the static versions avoid the unnecessary object creation.
  • org.openrewrite.staticanalysis.NoRedundantJumpStatements
    • Jump statements should not be redundant
    • Jump statements such as return and continue let you change the default flow of program execution, but jump statements that direct the control flow to the original direction are just a waste of keystrokes.
  • org.openrewrite.staticanalysis.NoToStringOnStringType
    • Unnecessary String#toString
    • Remove unnecessary String#toString invocations on objects which are already a string. Calling toString() on something that is already a String is redundant and clutters the code.
  • org.openrewrite.staticanalysis.NoValueOfOnStringType
    • Unnecessary String#valueOf(..)
    • Replace unnecessary String#valueOf(..) method invocations with the argument directly. This occurs when the argument to String#valueOf(arg) is a string literal, such as String.valueOf(&quot;example&quot;). Or, when the String#valueOf(..) invocation is used in a concatenation, such as &quot;example&quot; + String.valueOf(&quot;example&quot;). The wrapping call is redundant since Java already performs the conversion implicitly in these contexts.
  • org.openrewrite.staticanalysis.NullableOnMethodReturnType
    • Move @Nullable method annotations to the return type
    • This is the way the cool kids do it. Only annotations declared with @Target(ElementType.TYPE_USE) are moved, as the return type is a type context; declaration annotations such as javax.annotation.Nullable are left on the method.
  • org.openrewrite.staticanalysis.ObjectFinalizeCallsSuper
    • finalize() calls super
    • Overrides of Object#finalize() should call super. Skipping the super call can prevent parent classes from releasing critical system resources during garbage collection.
  • org.openrewrite.staticanalysis.OnlyCatchDeclaredExceptions
    • Replace catch(Exception) with specific declared exceptions thrown in the try block
    • Replaces catch(Exception e) blocks with a multi-catch block (catch (SpecificException1 | SpecificException2 e)) containing only the exceptions declared thrown by method or constructor invocations within the try block that are not already caught by more specific catch clauses. Catching a broad Exception type can unintentionally swallow runtime exceptions that indicate programming errors, making bugs harder to detect and diagnose.
  • org.openrewrite.staticanalysis.OperatorWrap
    • Operator wrapping
    • Fixes line wrapping policies on operators.
  • org.openrewrite.staticanalysis.PreferEqualityComparisonOverDifferenceCheck
    • Prefer direct comparison of numbers
    • Replace a - b == 0 with a == b, a - b != 0 with a != b, a - b &lt; 0 with a &lt; b, and similar transformations for all comparison operators to improve readability and avoid overflow issues.
  • org.openrewrite.staticanalysis.PreferIncrementOperator
    • Prefer increment/decrement and compound assignment operators
    • Prefer the use of increment and decrement operators (++, --, +=, -=) over their more verbose equivalents.
  • org.openrewrite.staticanalysis.PreferSystemGetPropertyOverGetenv
    • Prefer System.getProperty(&quot;user.home&quot;) over System.getenv(&quot;HOME&quot;)
    • Replaces System.getenv(&quot;HOME&quot;) with System.getProperty(&quot;user.home&quot;) for better portability.
  • org.openrewrite.staticanalysis.PrimitiveWrapperClassConstructorToValueOf
    • Use primitive wrapper valueOf method
    • The constructor of all primitive types has been deprecated in favor of using the static factory method valueOf available for each of the primitive type wrappers. Using valueOf enables object caching for frequently used values, reducing unnecessary heap allocations. Note that this changes identity semantics: valueOf may return cached instances (such as Boolean.TRUE or Integer values in [-128, 127]), so code that compares boxed values with ==/!=, relies on System.identityHashCode, or synchronizes on the boxed value may behave differently after this change.
  • org.openrewrite.staticanalysis.RedundantFileCreation
    • Redundant file creation
    • Remove unnecessary intermediate creations of files.
  • org.openrewrite.staticanalysis.ReferentialEqualityToObjectEquals
    • Replace referential equality operators with Object equals method invocations when the operands both override Object.equals(Object obj)
    • Using == or != compares object references, not the equality of two objects. This modifies code where both sides of a binary operation (== or !=) override Object.equals(Object obj) except when the comparison is within an overridden Object.equals(Object obj) method declaration itself. The resulting transformation must be carefully reviewed since any modifications change the program's semantics. When a class defines its own notion of equality through equals, using reference comparison is almost always a bug that causes logically identical objects to be treated as different.
  • org.openrewrite.staticanalysis.RemoveCallsToObjectFinalize
    • Remove Object.finalize() invocations
    • Remove calls to Object.finalize(). This method is called during garbage collection and calling it manually is misleading. Explicit finalize invocations can trigger resource cleanup prematurely while the object is still in use, leading to unpredictable behavior.
  • org.openrewrite.staticanalysis.RemoveCallsToSystemGc
    • Remove garbage collection invocations
    • Removes calls to System.gc() and Runtime.gc(). When to invoke garbage collection is best left to the JVM. Manual GC calls produce unpredictable results across different JVM implementations and can cause unnecessary application pauses.
  • org.openrewrite.staticanalysis.RemoveDuplicateAnnotations
    • Remove duplicate annotations
    • Remove annotations that are repeated on the same element, keeping only the first occurrence. Duplicates typically arise when several distinct annotations are migrated to a single new annotation, such as when both javax.annotation.Nullable and javax.annotation.CheckForNull become org.jspecify.annotations.Nullable. @Repeatable annotations are left alone, as repeating those is meaningful.
  • org.openrewrite.staticanalysis.RemoveDuplicateConditions
    • Related "if/else if" conditions should not be the same
    • When an if/else if chain contains the same condition more than once, the second branch can never execute because the first matching branch always wins. The duplicate branch is dead code and should be removed.
  • org.openrewrite.staticanalysis.RemoveEmptyJavaDocParameters
    • Remove JavaDoc @param, @return, and @throws with no description
    • Removes @param, @return, and @throws with no description from JavaDocs.
  • org.openrewrite.staticanalysis.RemoveExtraSemicolons
    • Remove extra semicolons
    • Removes not needed semicolons. Semicolons are considered not needed: * Optional semicolons at the end of try-with-resources, * after the last enum value if no field or method is defined, * no statement between two semicolon. Stray semicolons are typically typos or remnants of refactoring and can mislead readers into thinking a statement is present.
  • org.openrewrite.staticanalysis.RemoveHashCodeCallsFromArrayInstances
    • hashCode() should not be called on array instances
    • Replace hashCode() calls on arrays with Arrays.hashCode() because the results from hashCode() are not helpful. Arrays inherit hashCode() from Object, which returns an identity-based value unrelated to the array contents, so two arrays with identical elements will produce different hash codes.
  • org.openrewrite.staticanalysis.RemoveInstanceOfPatternMatch
    • Removes from code Java 14's instanceof pattern matching
    • Adds an explicit variable declaration at the beginning of if statement instead of instanceof pattern matching.
  • org.openrewrite.staticanalysis.RemoveJavaDocAuthorTag
    • Remove author tags from JavaDocs
    • Removes author tags from JavaDocs to reduce code maintenance.
  • org.openrewrite.staticanalysis.RemoveMethodsOnlyCallSuper
    • Remove methods that only call super
    • Methods that override a parent method but only call super with the same arguments are redundant and should be removed.
  • org.openrewrite.staticanalysis.RemoveNoArgumentSuperConstructorCall
    • Remove no argument super() constructor calls
    • The compiler inserts a call to the no argument constructor of the super class when a constructor does not start with an explicit this() or super(..) call, which makes writing out super(); redundant.
  • org.openrewrite.staticanalysis.RemoveRedundantNullCheckBeforeInstanceof
    • Remove redundant null checks before instanceof
    • Removes redundant null checks before instanceof operations since instanceof returns false for null. Removing the extra check simplifies the conditional and makes the null-safety guarantee of instanceof more visible to readers.
  • org.openrewrite.staticanalysis.RemoveRedundantNullCheckBeforeLiteralEquals
    • Remove redundant null checks before literal equals
    • Removes redundant null checks before equals() comparisons when the receiver is a literal string, since literals can never be null and equals() returns false for null arguments.
  • org.openrewrite.staticanalysis.RemoveRedundantTypeCast
    • Remove redundant casts
    • Removes unnecessary type casts. Does not currently check casts in lambdas and class constructors. Redundant casts add visual noise and can obscure the actual type relationships in the code, making it harder to follow the data flow.
  • org.openrewrite.staticanalysis.RemoveSelfAssignment
    • Variables should not be self-assigned
    • Self-assignments such as x = x have no effect and indicate a copy-paste error or typo where the left-hand or right-hand side should reference a different variable.
  • org.openrewrite.staticanalysis.RemoveSystemOutPrintln
    • Remove System.out#println statements
    • Print statements are often left accidentally after debugging an issue. This recipe removes all System.out#println and System.err#println statements from the code. Production code should use a proper logging framework which provides consistent formatting, configurable log levels, and centralized output control.
  • org.openrewrite.staticanalysis.RemoveToStringCallsFromArrayInstances
    • Remove toString() calls on arrays
    • The result from toString() calls on arrays is largely useless. The output does not actually reflect the contents of the array. Arrays.toString(array) should be used instead as it gives the contents of the array. Since arrays do not override toString() from Object, calling it produces only the type name and memory address, which is rarely what was intended.
  • org.openrewrite.staticanalysis.RemoveUnconditionalValueOverwrite
    • Map values should not be replaced unconditionally
    • When map.put(key, value) is called twice in a row with the same key, the first call is dead code because its value is immediately overwritten. Remove the first call to make the intent clear.
  • org.openrewrite.staticanalysis.RemoveUnneededAssertion
    • Remove unneeded assertions
    • Remove unneeded assertions like assert true, assertTrue(true), or assertFalse(false).
  • org.openrewrite.staticanalysis.RemoveUnneededBlock
    • Remove unneeded block
    • Flatten blocks into inline statements when possible. Unnecessary nested blocks add indentation and scope boundaries that obscure the control flow, often indicating code that should be extracted into its own method.
  • org.openrewrite.staticanalysis.RemoveUnreachableMultiCatchAlternative
    • Remove unreachable catch alternatives shadowed by earlier catch clauses
    • When an earlier catch clause already covers a type, any later catch (including a multi-catch alternative) for the same type or a subtype is unreachable and is a Java compile error. This commonly appears after type-substitution migrations (for example, renaming an exception so that two catch clauses end up overlapping). This recipe drops the unreachable alternatives from later multi-catches, collapses a multi-catch to a regular catch when only one alternative remains, and removes the entire catch clause when all of its declared types are already covered.
  • org.openrewrite.staticanalysis.RemoveUnusedLabels
    • Remove unused labels
    • Remove labels that are not referenced by any break or continue statement.
  • org.openrewrite.staticanalysis.RemoveUnusedLocalVariables
    • Remove unused local variables
    • If a local variable is declared but not used, it is dead code and should be removed. Unused variables increase cognitive load for readers who must determine whether the variable matters, and they may signal incomplete implementations or missed refactoring.
  • org.openrewrite.staticanalysis.RemoveUnusedPrivateFields
    • Remove unused private fields
    • If a private field is declared but not used in the program, it can be considered dead code and should therefore be removed. Dead fields clutter the class, increase its memory footprint, and can mislead developers into thinking they are part of the class's behavior.
  • org.openrewrite.staticanalysis.RemoveUnusedPrivateMethods
    • Remove unused private methods
    • private methods that are never executed are dead code and should be removed. Keeping unreachable methods around adds maintenance burden and can give a false impression of the class's capabilities.
  • org.openrewrite.staticanalysis.RenameExceptionInEmptyCatch
    • Rename caught exceptions in empty catch blocks to ignored
    • Renames caught exceptions in empty catch blocks to ignored. ignored will be incremented by 1 if a namespace conflict exists.
  • org.openrewrite.staticanalysis.RenameLocalVariablesToCamelCase
    • Reformat local variable names to camelCase
    • Reformat local variable and method parameter names to camelCase to comply with Java naming convention. The recipe will not rename variables declared in for loop controls or catches with a single character. The first character is set to lower case and existing capital letters are preserved. Special characters that are allowed in java field names $ and _ are removed (unless the name starts with one). If a special character is removed the next valid alphanumeric will be capitalized. Currently, does not support renaming members of classes. The recipe will not rename a variable if the result already exists in the class, conflicts with a java reserved keyword, or the result is blank. Consistent naming conventions improve readability and reduce friction when navigating unfamiliar code.
  • org.openrewrite.staticanalysis.RenameMethodsNamedHashcodeEqualOrToString
    • Rename methods named hashcode, equal, or tostring
    • Methods should not be named hashcode, equal, or tostring. Any of these are confusing as they appear to be intended as overridden methods from the Object base class, despite being case-insensitive. These near-miss names are almost certainly spelling mistakes that silently introduce a new method instead of overriding the intended one.
  • org.openrewrite.staticanalysis.RenamePrivateFieldsToCamelCase
    • Reformat private field names to camelCase
    • Reformat private field names to camelCase to comply with Java naming convention. The recipe will not rename fields with default, protected or public access modifiers. The recipe will not rename private constants. The first character is set to lower case and existing capital letters are preserved. Special characters that are allowed in java field names $ and _ are removed. If a special character is removed the next valid alphanumeric will be capitalized. The recipe will not rename a field if the result already exists in the class, conflicts with a java reserved keyword, or the result is blank. Consistent naming conventions improve code readability and help developers quickly understand the purpose and scope of fields.
  • org.openrewrite.staticanalysis.ReorderAnnotationAttributes
    • Reorder annotation attributes alphabetically
    • Reorder annotation attributes to be alphabetical. Positional arguments (those without explicit attribute names) are left in their original position.
  • org.openrewrite.staticanalysis.ReorderAnnotations
    • Reorder annotations alphabetically
    • Consistently order annotations by comparing their simple name.
  • org.openrewrite.staticanalysis.ReplaceApacheCommonsLang3ValidateNotNullWithObjectsRequireNonNull
    • Replace org.apache.commons.lang3.Validate#notNull with Objects#requireNonNull
    • Replace org.apache.commons.lang3.Validate.notNull(..) with Objects.requireNonNull(..).
  • org.openrewrite.staticanalysis.ReplaceClassIsInstanceWithInstanceof
    • Replace A.class.isInstance(a) with a instanceof A
    • There should be no A.class.isInstance(a), it should be replaced by a instanceof A. Using instanceof enables the compiler to catch type incompatibilities at compile time rather than silently passing at runtime, which helps detect dead code early.
  • org.openrewrite.staticanalysis.ReplaceCollectionToArrayArgWithEmptyArray
    • Use Empty Array for Collection.toArray()
    • Changes new array creation with Collection#toArray(T[]) to use an empty array argument, which is better for performance. According to the Collection#toArray(T[]) documentation: > If the collection fits in the specified array, it is returned therein. However, although it's not intuitive, allocating a right-sized array ahead of time to pass to the API appears to be generally worse for performance according to benchmarking and JVM developers due to a number of implementation details in both Java and the virtual machine. H2 achieved significant performance gains by switching to empty arrays instead pre-sized ones.
  • org.openrewrite.staticanalysis.ReplaceDeprecatedRuntimeExecMethods
    • Replace deprecated Runtime#exec() methods
    • Replace Runtime#exec(String) methods to use exec(String[]) instead because the former is deprecated after Java 18 and is no longer recommended for use by the Java documentation.
  • org.openrewrite.staticanalysis.ReplaceDuplicateStringLiterals
    • Replace duplicate String literals
    • Replaces String literals with a length of 5 or greater repeated a minimum of 3 times. Qualified String literals include final Strings, method invocations, and new class invocations. Adds a new private static final String or uses an existing equivalent class field. A new variable name will be generated based on the literal value if an existing field does not exist. The generated name will append a numeric value to the variable name if a name already exists in the compilation unit. Centralizing repeated string values into constants makes refactoring safer and reduces the risk of inconsistent updates.
  • org.openrewrite.staticanalysis.ReplaceHashtableWithHashMap
    • Replace java.util.Hashtable with java.util.HashMap
    • Hashtable synchronizes every operation, which adds overhead in the common single-threaded case. This recipe replaces a local Hashtable with a HashMap when data flow analysis can prove the Hashtable never escapes its method (it is not returned, assigned to a field, or passed as an argument), so no other thread can observe it and the synchronization is redundant. Fields, escaping variables, and Hashtable-specific method usages (contains, elements, keys) are left untouched. HashMap permits null keys and values, so it accepts every input Hashtable did.
  • org.openrewrite.staticanalysis.ReplaceLambdaWithMethodReference
    • Use method references in lambda
    • Replaces the single statement lambdas o -&gt; o instanceOf X, o -&gt; (A) o, o -&gt; System.out.println(o), o -&gt; o != null, o -&gt; o == null with the equivalent method reference. Method references are often more concise and readable than their lambda equivalents, making the code's intent clearer at a glance.
  • org.openrewrite.staticanalysis.ReplaceOptionalIsPresentWithIfPresent
    • Replace Optional#isPresent() with Optional#ifPresent()
    • Replace Optional#isPresent() with Optional#ifPresent(). Please note that this recipe is only suitable for if-blocks that lack an Else-block and have a single condition applied.
  • org.openrewrite.staticanalysis.ReplaceRedundantFormatWithPrintf
    • Replace redundant String format invocations that are wrapped with PrintStream operations
    • Replaces PrintStream.print(String.format(format, ...args)) with PrintStream.printf(format, ...args) (and for println, appends a newline to the format string).
  • org.openrewrite.staticanalysis.ReplaceStackWithDeque
    • Replace java.util.Stack with java.util.Deque
    • From the Javadoc of Stack: > A more complete and consistent set of LIFO stack operations is provided by the Deque interface and its implementations, which should be used in preference to this class. Stack inherits from Vector, which carries unnecessary synchronization overhead in single-threaded contexts and exposes non-stack operations like random index access.
  • org.openrewrite.staticanalysis.ReplaceStringBufferWithStringBuilder
    • Replace java.lang.StringBuffer with java.lang.StringBuilder
    • StringBuffer synchronizes every operation, which adds overhead in the common single-threaded case. StringBuilder exposes the identical API without the synchronization. This recipe replaces a local StringBuffer with a StringBuilder when data flow analysis can prove the StringBuffer never escapes its method (it is not returned, assigned to a field, or passed as an argument), so no other thread can observe it and the synchronization is redundant. Fields and escaping variables are left untouched.
  • org.openrewrite.staticanalysis.ReplaceStringBuilderWithString
    • Replace StringBuilder#append with String
    • Replace StringBuilder.append() with String if you are only concatenating a small number of strings and the code is simple and easy to read, as the compiler can optimize simple string concatenation expressions into a single String object, which can be more efficient than using StringBuilder.
  • org.openrewrite.staticanalysis.ReplaceStringConcatenationWithStringValueOf
    • Replace String concatenation with String.valueOf()
    • Replace inefficient string concatenation patterns like &quot;&quot; + ... with String.valueOf(...). This improves code readability and may have minor performance benefits. The empty string prefix &quot;&quot; + is an indirect way to convert a value to a String, while String.valueOf() clearly communicates the conversion intent.
  • org.openrewrite.staticanalysis.ReplaceTextBlockWithString
    • Replace text block with regular string
    • Replace text block with a regular multi-line string. Text blocks that fit on a single line without concatenation or escaped newlines gain no readability benefit from the triple-quote syntax and are clearer as plain string literals.
  • org.openrewrite.staticanalysis.ReplaceThreadRunWithThreadStart
    • Replace calls to Thread.run() with Thread.start()
    • Thread.run() should not be called directly.
  • org.openrewrite.staticanalysis.ReplaceValidateNotNullHavingSingleArgWithObjectsRequireNonNull
    • Replace org.apache.commons.lang3.Validate#notNull with Objects#requireNonNull
    • Replace org.apache.commons.lang3.Validate.notNull(Object) with Objects.requireNonNull(Object).
  • org.openrewrite.staticanalysis.ReplaceValidateNotNullHavingVarargsWithObjectsRequireNonNull
    • Replace org.apache.commons.lang3.Validate#notNull with Objects#requireNonNull
    • Replace org.apache.commons.lang3.Validate.notNull(Object, String, Object[]) with Objects.requireNonNull(Object, String).
  • org.openrewrite.staticanalysis.ReplaceVectorWithArrayList
    • Replace java.util.Vector with java.util.ArrayList
    • Vector synchronizes every operation, which adds overhead in the common single-threaded case. This recipe replaces a local Vector with an ArrayList when data flow analysis can prove the Vector never escapes its method (it is not returned, assigned to a field, or passed as an argument), so no other thread can observe it and the synchronization is redundant. Fields, escaping variables, Vector-specific method usages (like elementAt or addElement), and the Vector(int, int) constructor are left untouched.
  • org.openrewrite.staticanalysis.ReplaceWeekYearWithYear
    • Week Year (YYYY) should not be used for date formatting
    • For most dates Week Year (YYYY) and Year (yyyy) yield the same results. However, on the last week of December and the first week of January, Week Year could produce unexpected results. This is a common source of off-by-one-year bugs that typically only manifest around New Year's Eve, making them difficult to catch during development and testing.
  • org.openrewrite.staticanalysis.SillyEqualsCheck
    • Silly equality checks should not be made
    • Detects .equals() calls that compare incompatible types and will always return false. Replaces .equals(null) with == null and array .equals() with Arrays.equals(). Flags comparisons between unrelated types or between arrays and non-arrays.
  • org.openrewrite.staticanalysis.SimplifyArraysAsList
    • Simplify Arrays.asList(..) with varargs
    • Simplifies Arrays.asList() method calls that use explicit array creation to use varargs instead. For example, Arrays.asList(new String[]\{&quot;a&quot;, &quot;b&quot;, &quot;c&quot;\}) becomes Arrays.asList(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;). Explicitly constructing an array to pass to a varargs parameter adds visual clutter without changing behavior, since the compiler generates the array automatically.
  • org.openrewrite.staticanalysis.SimplifyBooleanExpression
    • Simplify boolean expression
    • Checks for overly complicated boolean expressions, such as if (b == true), b || true, !false, etc. Needlessly complex boolean logic makes code harder to reason about and increases the chance of introducing errors during future modifications.
  • org.openrewrite.staticanalysis.SimplifyBooleanExpressionWithDeMorgan
    • Simplify boolean expressions using De Morgan's laws
    • Applies De Morgan's laws to simplify boolean expressions with negation. Transforms !(a &amp;&amp; b) to !a || !b and !(a || b) to !a &amp;&amp; !b. Distributing negations inward eliminates the outer ! and makes each individual condition's polarity immediately visible, which aids comprehension.
  • org.openrewrite.staticanalysis.SimplifyBooleanReturn
    • Simplify boolean return
    • Simplifies Boolean expressions by removing redundancies. For example, a &amp;&amp; true simplifies to a. Wrapping a boolean expression in an if-then-else just to return true or false adds unnecessary control flow that obscures the straightforward intent of the expression.
  • org.openrewrite.staticanalysis.SimplifyCompoundStatement
    • Simplify compound statement
    • Fixes or removes useless compound statements. For example, removing b &amp;= true, and replacing b &amp;= false with b = false.
  • org.openrewrite.staticanalysis.SimplifyConsecutiveAssignments
    • Simplify consecutive assignments
    • Combine consecutive assignments into a single statement where possible.
  • org.openrewrite.staticanalysis.SimplifyConstantIfBranchExecution
    • Simplify constant if branch execution
    • Checks for if expressions that are always true or false and simplifies them. Branches that can never execute are dead code that misleads readers and may mask logic errors introduced during refactoring.
  • org.openrewrite.staticanalysis.SimplifyDurationCreationUnits
    • Simplify java.time.Duration units
    • Simplifies java.time.Duration units to be more human-readable.
  • org.openrewrite.staticanalysis.SimplifyElseBranch
    • Simplify else branch if it only has a single if
    • Simplify else branch if it only has a single if.
  • org.openrewrite.staticanalysis.SimplifyForLoopBoundaryComparison
    • Simplify for loop boundary comparisons
    • Replace &lt;= with &lt; in for loop conditions by adjusting the comparison operands. For example, i &lt;= n - 1 simplifies to i &lt; n, and i &lt;= n becomes i &lt; n + 1.
  • org.openrewrite.staticanalysis.SimplifyRedundantLogicalExpression
    • Identical expressions used with logical operators should be simplified
    • When the same expression appears on both sides of &amp;&amp;, ||, &amp;, or |, the result is always equal to that expression. For example, x &amp;&amp; x is always just x. This is typically a copy-paste error where one side should have been different.
  • org.openrewrite.staticanalysis.SimplifyTernaryRecipes
    • Simplify ternary expressions
    • Simplifies various types of ternary expressions to improve code readability. Ternaries that simply select between true and false are redundant wrappers around the condition itself and add unnecessary complexity.
  • org.openrewrite.staticanalysis.SimplifyTernaryRecipes$SimplifyTernaryFalseTrueRecipe
    • Replace booleanExpression ? false : true with !booleanExpression
    • Replace ternary expressions like booleanExpression ? false : true with !booleanExpression.
  • org.openrewrite.staticanalysis.SimplifyTernaryRecipes$SimplifyTernaryTrueFalseRecipe
    • Replace booleanExpression ? true : false with booleanExpression
    • Replace ternary expressions like booleanExpression ? true : false with booleanExpression.
  • org.openrewrite.staticanalysis.SingleLineCommentSpacing
    • Add space after // in single-line comments
    • Ensures there is exactly one space after // in single-line comments when missing.
  • org.openrewrite.staticanalysis.SortedSetStreamToLinkedHashSet
    • Sorted set stream should be collected to LinkedHashSet
    • Converts set.stream().sorted().collect(Collectors.toSet()) to set.stream().sorted().collect(LinkedHashSet::new).
  • org.openrewrite.staticanalysis.StaticAccessViaInstance
    • Static members should be accessed via the class name
    • Accessing static fields or calling static methods on an instance reference is misleading. Static members should be accessed using the declaring class name instead.
  • org.openrewrite.staticanalysis.StaticMethodNotFinal
    • Static methods need not be final
    • Static methods do not need to be declared final because they cannot be overridden. Redundant modifiers add noise to the code and can suggest a misunderstanding of the language's dispatch model.
  • org.openrewrite.staticanalysis.StringLiteralEquality
    • Use String.equals() on String literals
    • String.equals() should be used when checking value equality on String literals. Using == or != compares object references, not the actual value of the Strings. This only modifies code where at least one side of the binary operation (== or !=) is a String literal, such as &quot;someString&quot; == someVariable;. This is to prevent inadvertently changing code where referential equality is the user's intent. Reference equality on strings is fragile because it depends on JVM string interning behavior, which can vary across runtimes and is not guaranteed for dynamically constructed strings.
  • org.openrewrite.staticanalysis.TernaryOperatorsShouldNotBeNested
    • Ternary operators should not be nested
    • Nested ternary operators can be hard to read quickly. Prefer simpler constructs for improved readability. If supported, this recipe will try to replace nested ternaries with switch expressions. Deeply nested conditional expressions obscure the branching logic and make it easy to misread which value corresponds to which condition.
  • org.openrewrite.staticanalysis.TypecastParenPad
    • Typecast parenthesis padding
    • Fixes whitespace padding between a typecast type identifier and the enclosing left and right parentheses. For example, when configured to remove spacing, ( int ) 0L; becomes (int) 0L;.
  • org.openrewrite.staticanalysis.URLEqualsHashCodeRecipes
    • URL Equals and Hash Code
    • Uses of equals() and hashCode() cause java.net.URL to make blocking internet connections. Instead, use java.net.URI.
  • org.openrewrite.staticanalysis.URLEqualsHashCodeRecipes$URLEqualsRecipe
    • URL Equals
    • Uses of equals() cause java.net.URL to make blocking internet connections. Instead, use java.net.URI.
  • org.openrewrite.staticanalysis.URLEqualsHashCodeRecipes$URLHashCodeRecipe
    • URL Hash Code
    • Uses of hashCode() cause java.net.URL to make blocking internet connections. Instead, use java.net.URI.
  • org.openrewrite.staticanalysis.UnnecessaryCatch
    • Remove catch for a checked exception if the try block does not throw that exception
    • A refactoring operation may result in a checked exception that is no longer thrown from a try block. This recipe will find and remove unnecessary catch blocks.
  • org.openrewrite.staticanalysis.UnnecessaryCloseInTryWithResources
    • Unnecessary close in try-with-resources
    • Remove unnecessary AutoCloseable#close() statements in try-with-resources. Try-with-resources already guarantees that each declared resource is closed when the block exits, so an explicit close() call is redundant and can be confusing.
  • org.openrewrite.staticanalysis.UnnecessaryExplicitTypeArguments
    • Unnecessary explicit type arguments
    • When explicit type arguments are inferable by the compiler, they may be removed.
  • org.openrewrite.staticanalysis.UnnecessaryFinalInTryWithResources
    • Unnecessary final in try-with-resources
    • Remove the redundant final modifier from resources declared in a try-with-resources statement. Such resources are implicitly final, so the modifier adds no meaning.
  • org.openrewrite.staticanalysis.UnnecessaryParentheses
    • Remove unnecessary parentheses
    • Removes unnecessary parentheses from code where extra parentheses pairs are redundant. Redundant parentheses add visual noise and can obscure the actual structure of an expression, making code harder to read at a glance.
  • org.openrewrite.staticanalysis.UnnecessaryPrimitiveAnnotations
    • Remove @Nullable and @CheckForNull annotations from primitives
    • Primitives can't be null anyway, so these annotations are not useful in this context. Leaving them in place gives the false impression that a null value is possible, which can confuse readers and static analysis tools alike.
  • org.openrewrite.staticanalysis.UnnecessaryReturnAsLastStatement
    • Unnecessary return as last statement in void method
    • Removes return from a void method if it's the last statement. A trailing return in a void method has no effect on control flow and is just noise that distracts from the meaningful logic.
  • org.openrewrite.staticanalysis.UnnecessaryThrows
    • Unnecessary throws
    • Remove unnecessary throws declarations. This recipe will only remove unused, checked exceptions if: - The declaring class or the method declaration is final. - The method declaration is static or private. - The method overrides a method declaration in a super class and the super class does not throw the exception. - The method is public and the exception is not documented via a JavaDoc as a @throws tag. The throws declaration is retained on overridable methods (package-private and protected methods on non-final classes), and on public methods overridden within the same source file, so that a subclass override which does throw the exception keeps compiling. Overrides in other source files cannot be detected without a scanning recipe and are therefore not accounted for. A throws declaration is also retained when the method body contains a call whose type does not fully resolve, because such a call may throw the exception. When a throws declaration is removed, any @throws or @exception JavaDoc tag documenting that exception is removed along with it, so that the documentation does not describe an exception the method no longer declares. Declaring exceptions that are never thrown misleads callers into writing unnecessary error-handling code and obscures the method's true behavior.
  • org.openrewrite.staticanalysis.UnwrapElseAfterReturn
    • Unwrap else block after return or throw statement
    • Unwraps the else block when the if block ends with a return or throw statement, reducing nesting and improving code readability.
  • org.openrewrite.staticanalysis.UnwrapRepeatableAnnotations
    • Unwrap @Repeatable annotations
    • Java 8 introduced the concept of @Repeatable annotations, making the wrapper annotation unnecessary. Using the repeatable form directly reduces nesting and makes the individual annotations easier to scan.
  • org.openrewrite.staticanalysis.UpperCaseLiteralSuffixes
    • Upper case literal suffixes
    • Using upper case literal suffixes for declaring literals is less ambiguous, e.g., 1l versus 1L. A lowercase l is easily mistaken for the digit 1 in many fonts, which can lead to incorrect assumptions about the value. Hexadecimal digits are upper cased as well, e.g., 0Xabc versus 0xABC, such that they stand out from the lower case 0x prefix and p exponent.
  • org.openrewrite.staticanalysis.UseAsBuilder
    • Chain calls to builder methods
    • Chain calls to builder methods that are on separate lines into one chain of builder calls.
  • org.openrewrite.staticanalysis.UseCollectionInterfaces
    • Use Collection interfaces
    • Use Deque, List, Map, ConcurrentMap, Queue, and Set instead of implemented collections. Replaces the return type of public method declarations and the variable type public variable declarations. Programming to an interface rather than a concrete collection type decouples callers from a specific implementation, making it easier to swap data structures later without breaking dependent code.
  • org.openrewrite.staticanalysis.UseDiamondOperator
    • Use the diamond operator
    • The diamond operator (&lt;&gt;) should be used. Java 7 introduced the diamond operator to reduce the verbosity of generics code. For instance, instead of having to declare a List's type in both its declaration and its constructor, you can now simplify the constructor declaration with &lt;&gt;, and the compiler will infer the type. Repeating type arguments that the compiler can already deduce is unnecessary boilerplate that clutters the code.
  • org.openrewrite.staticanalysis.UseForEachRemoveInsteadOfSetRemoveAll
    • Replace java.util.Set#removeAll(java.util.Collection) with java.util.Collection#forEach(Set::remove)
    • Using java.util.Collection#forEach(Set::remove) rather than java.util.Set#removeAll(java.util.Collection) may improve performance due to a possible O(n^2) complexity.
  • org.openrewrite.staticanalysis.UseJavaStyleArrayDeclarations
    • No C-style array declarations
    • Change C-Style array declarations int i[]; to int[] i;. Keeping the brackets with the type groups all type information in one place, so readers do not have to inspect both the type and the variable name to determine whether something is an array.
  • org.openrewrite.staticanalysis.UseLambdaForFunctionalInterface
    • Use lambda expressions instead of anonymous classes
    • Instead of anonymous class declarations, use a lambda where possible. Using lambdas to replace anonymous classes can lead to more expressive and maintainable code, improve code readability, reduce code duplication, and achieve better performance in some cases.
  • org.openrewrite.staticanalysis.UseListSort
    • Replace invocations of Collections#sort(List, Comparator) with List#sort(Comparator)
    • The java.util.Collections#sort(..) implementation defers to the java.util.List#sort(Comparator), replaced it with the java.util.List#sort(Comparator) implementation for better readability.
  • org.openrewrite.staticanalysis.UseMapContainsKey
    • Use Map#containsKey
    • map.keySet().contains(a) can be simplified to map.containsKey(a).
  • org.openrewrite.staticanalysis.UseMapEntrySetIteration
    • Iterate a Map's entrySet() rather than its keySet()
    • A loop over map.keySet() that calls map.get(key) hashes and probes the map again for every element, which on a TreeMap costs an extra O(log n) lookup per iteration. Iterating map.entrySet() instead hands the loop both the key and the value. The loop is only rewritten when: - The map is a simple reference that is neither modified nor reassigned inside the loop. - get is called only with the loop variable. - The loop variable is neither reassigned nor captured by a lambda or anonymous class. Every candidate loop, converted or not, is recorded in a data table along with the reason it was left alone.
  • org.openrewrite.staticanalysis.UseObjectNotifyAll
    • Replaces Object.notify() with Object.notifyAll()
    • Object.notifyAll() and Object.notify() both wake up sleeping threads, but Object.notify() only rouses one while Object.notifyAll() rouses all of them. Since Object.notify() might not wake up the right thread, Object.notifyAll() should be used instead. See this for more information. Using notify() in a multi-waiter scenario risks leaving threads permanently stalled when the wrong one is awakened.
  • org.openrewrite.staticanalysis.UsePortableNewlines
    • Use %n instead of \n in format strings
    • Format strings should use %n rather than \n to produce platform-specific line separators. Hard-coded \n characters produce incorrect line endings on Windows, whereas %n adapts to the runtime platform automatically.
  • org.openrewrite.staticanalysis.UseStandardCharset
    • Use StandardCharset constants
    • Replaces Charset.forName(java.lang.String) with the equivalent StandardCharset constant. Using the predefined constants is both compile-time safe and avoids the need to handle UnsupportedEncodingException for charsets that are guaranteed to exist on every JVM.
  • org.openrewrite.staticanalysis.UseStringCaseInsensitiveOrderRecipe
    • Use String.CASE_INSENSITIVE_ORDER
    • Replaces case-insensitive string comparator lambdas and method references with the JDK constant String.CASE_INSENSITIVE_ORDER. Improves readability and removes one closure allocation per call site.
  • org.openrewrite.staticanalysis.UseStringReplace
    • Use String::replace() when first parameter is not a real regular expression
    • When String::replaceAll is used, the first argument should be a real regular expression. If it’s not the case, String::replace does exactly the same thing as String::replaceAll without the performance drawback of the regex.
  • org.openrewrite.staticanalysis.UseSystemLineSeparator
    • Use System.lineSeparator()
    • Replace calls to System.getProperty(&quot;line.separator&quot;) with System.lineSeparator().
  • org.openrewrite.staticanalysis.UseTryWithResources
    • Use try-with-resources
    • Refactor try/finally blocks to use try-with-resources when the finally block only closes an AutoCloseable resource. Try-with-resources guarantees that resources are closed even when exceptions occur, eliminating an entire class of resource-leak bugs that manual finally blocks are prone to.
  • org.openrewrite.staticanalysis.WhileInsteadOfFor
    • Prefer while over for loops
    • When only the condition expression is defined in a for loop, and the initialization and increment expressions are missing, a while loop should be used instead to increase readability. A for loop with empty init and update sections signals iteration mechanics that do not exist, whereas while clearly communicates a simple conditional loop.
  • org.openrewrite.staticanalysis.WriteOctalValuesAsDecimal
    • Write octal values as decimal
    • Developers may not recognize octal values as such, mistaking them instead for decimal values. Because a leading zero silently switches the literal to base-8, what looks like 010 actually represents 8, which is a common source of subtle numeric bugs.
  • org.openrewrite.staticanalysis.java.MoveFieldAnnotationToType
    • Move annotation to type instead of field
    • Annotations that could be applied to either a field or a type are better applied to the type, because similar annotations may be more restrictive, leading to compile errors like 'scoping construct cannot be annotated with type-use annotation' when migrating later.
  • org.openrewrite.staticanalysis.maven.MavenJavadocNonAsciiRecipe
    • Remove non-ASCII characters from Javadoc
    • Maven's javadoc-plugin configuration does not support non-ASCII characters. What makes it tricky is the error is very ambiguous and doesn't help in any way. This recipe removes those non-ASCII characters.

rewrite-static-analysis-python​

License: Moderne Proprietary License

87 recipes

rewrite-struts​

License: Moderne Proprietary License

22 recipes

rewrite-terraform​

License: Moderne Proprietary License

139 recipes

rewrite-testing-frameworks​

License: Moderne Source Available License

303 recipes

rewrite-third-party​

License: Apache License Version 2.0

1693 recipes