Java and Maven tools for OpenRewrite import ordering and POM dependency management

version
1.42.0
GitHub stars
20

Install

/plugin install java@motlin-claude-code-plugins

Run it inside Claude Code after adding the marketplace with /plugin marketplace add motlin/claude-code-plugins.

Contents

Discovered from source

Skills 3

Maven CLI

Avoid -o / --offline

Do not pass -o or --offline by default.

In multi-worktree or multi-branch projects, ~/.m2/repository holds artifacts installed by other worktrees, possibly compiled against different transitive versions than this branch resolves. Offline mode makes Maven trust those cached sibling modules instead of rebuilding them, producing phantom compile errors that look like upstream defects. Example: a sibling module compiled against Dropwizard 3 leaking io.dropwizard.core.ConfiguredBundle references into a Dropwizard 2 build.

To verify a module compiles, use mvn -pl <module> -am compile (or clean install -DskipTests). -am rebuilds upstream siblings from this worktree's source. If -am fails on an upstream module, fix that root cause rather than falling back to -o.

Use -o only when the cache is known to match HEAD (for example, right after a successful mvn install from the same branch) or when testing offline behavior specifically.

Don't use stash-and-rerun to acquit your diff

git stash && mvn ... failing with the same error does not prove the diff innocent. Both runs resolve from the same ~/.m2 cache, so a polluted cache fails identically either way.

Reproduce against a freshly built dependency graph instead: mvn -pl <module> -am clean install -DskipTests. If it succeeds, the earlier failure was cache pollution. If it still fails, the failure is real.

Prefer -pl <module> -am over building everything

During development, scope builds to the changed module plus its upstream dependencies. It is faster than a root build and uses the exact classpath the module sees. Save full reactor builds for release verification or changes spanning many modules.

OpenRewrite Recipes

MethodMatcher

Use wildcards instead of enumerating methods

// BAD: separate matcher per variant
private static final MethodMatcher IS_TRACE_ENABLED = new MethodMatcher("org.slf4j.Logger isTraceEnabled()");
private static final MethodMatcher IS_DEBUG_ENABLED = new MethodMatcher("org.slf4j.Logger isDebugEnabled()");
// ... repeated for info, warn, error, plus marker overloads = 10 matchers

// GOOD: single wildcard matcher
private static final MethodMatcher IS_X_ENABLED = new MethodMatcher("org.slf4j.Logger is*Enabled(..)");

This also simplifies Preconditions.check():

// BAD
Preconditions.check(or(
    new UsesMethod<>(IS_TRACE_ENABLED),
    new UsesMethod<>(IS_DEBUG_ENABLED),
    // ... 8 more
), visitor);

// GOOD
Preconditions.check(new UsesMethod<>(IS_X_ENABLED), visitor);

Use MethodMatcher for method+type validation

Instead of manually checking method name and receiver type:

// BAD
if (!"getMessage".equals(method.getSimpleName())) return false;
Expression select = method.getSelect();
if (select == null) return false;
return TypeUtils.isAssignableTo("java.lang.Throwable", select.getType());

// GOOD
private static final MethodMatcher GET_MESSAGE = new MethodMatcher("java.lang.Throwable getMessage()");
// then: GET_MESSAGE.matches(argument)

TypeUtils

Use isOfClassType() instead of manual FQN comparison

// BAD
JavaType.FullyQualified type = TypeUtils.asFullyQualified(select.getType());
return type != null && "org.slf4j.Logger".equals(type.getFullyQualifiedName());

// GOOD
TypeUtils.isOfClassType(select.getType(), "org.slf4j.Logger")

Use TypeUtils.isOfType() instead of FQN string equality

// BAD
currentType.getFullyQualifiedName().equals(targetType.getFullyQualifiedName())

// GOOD
TypeUtils.isOfType(currentType, targetType)

Handle inheritance with isAssignableTo()

When matching a member's declaring type against the current class, check both exact match and subtype. Otherwise inherited members get attributed to the superclass:

// BAD: misses inherited members
if (TypeUtils.isOfType(currentType, declaringType)) { ... }

// GOOD: handles both direct and inherited members
if (TypeUtils.isOfType(currentType, declaringType) ||
        TypeUtils.isAssignableTo(declaringType.getFullyQualifiedName(), currentType)) { ... }

Use the FQN-based isAssignableTo overload to handle parameterized types correctly.

Use instanceof JavaType.FullyQualified not JavaType.Class

JavaType.Class extends JavaType.FullyQualified, so instanceof JavaType.Class is too narrow for checks like fieldType.getOwner().

ListUtils for Statement Transformations

Use ListUtils.flatMap() instead of manual ArrayList + modified flag

// BAD
List<Statement> newStatements = new ArrayList<>();
boolean modified = false;
for (Statement stmt : visited.getStatements()) {
    if (shouldTransform(stmt)) {
        newStatements.addAll(extractStatements(stmt));
        modified = true;
    } else {
        newStatements.add(stmt);
    }
}
if (modified) return visited.withStatements(newStatements);
return visited;

// GOOD
return visited.withStatements(ListUtils.flatMap(visited.getStatements(), stmt -> {
    if (shouldTransform(stmt)) {
        return extractStatements(stmt); // return List = replace with multiple
    }
    return stmt; // return single item = keep as-is
}));

Use ListUtils.map() and ListUtils.mapFirst() for whitespace adjustments

List<Statement> bodyStatements = ListUtils.map(
    extractStatements(ifStmt.getThenPart()),
    st -> st.withPrefix(Space.build(whitespace, emptyList())));
return ListUtils.mapFirst(bodyStatements,
    first -> first.withPrefix(ifStmt.getPrefix()));

Recipe Composition

Don't duplicate logic handled by earlier recipes

In a composition (e.g., Slf4jBestPractices), earlier recipes transform the code before later ones see it. Don't handle cases an earlier recipe already covers.

Example: RemoveUnnecessaryLogLevelGuards should not treat string concatenation ("Name: " + name) as safe to unguard. The ParameterizedLogging recipe runs first and converts concatenation to parameterized form. If concatenation still exists when the guard-removal recipe runs, the guard is still needed for performance.

AST Construction

Use JavaElementFactory for common nodes

// BAD: verbose manual construction
new J.Identifier(Tree.randomId(), Space.EMPTY, Markers.EMPTY, emptyList(), "this", ownerType, null)

// GOOD: factory method
JavaElementFactory.newThis(ownerType)

Use Flag enum and modifier helpers instead of magic bitmasks

// BAD: magic number
(fieldType.getFlagsBitMap() & 0x0008L) != 0

// GOOD: readable API
fieldType.hasFlags(Flag.Static)
method.hasModifier(J.Modifier.Type.Static)

Language Scoping

Exclude non-target languages from Java-specific recipes

Java-specific recipes also run on Kotlin files unless excluded:

@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
    return Preconditions.check(
        Preconditions.not(new KotlinFileChecker<>()),
        new MyJavaVisitor()
    );
}

JavaTemplate Usage

Declare imports when the template introduces types

JavaTemplate template = JavaTemplate.builder("#{any()}.toArray(new #{}[0])")
        .imports(fqn)
        .build();

A template that introduces library types also needs a parser classpath:

JavaTemplate template = JavaTemplate
    .builder("Your.template.code()")
    .imports(
        "org.assertj.core.api.Assertions",
        "org.eclipse.collections.impl.utility.Iterate"
    )
    .javaParser(JavaParser.fromJavaVersion()
        .classpath("assertj-core", "eclipse-collections", "eclipse-collections-api")
    )
    .build();

Add .contextSensitive() only when the snippet needs its surroundings

Use it when the template refers to local variables, fields, or methods of the enclosing class. A self-contained snippet such as @BeforeAll static void setUp() {} should stay context-free: context-free templates are faster and can be cached.

Call maybeAddImport() after applying a template

Expression result = template.apply(...);
maybeAddImport(fqn);

Call maybeRemoveImport() for types the template no longer uses.

Visitor Patterns

JavaVisitor vs JavaIsoVisitor

Use JavaIsoVisitor when returning the same LST element type you visit. Use JavaVisitor when returning a different type, such as unwrapping J.Parentheses into its inner expression.

Handle parenthesized expressions

When an expression might be parenthesized, visit J.Parentheses nodes too. To replace the inner expression while keeping the parentheses and prefix, use visitedParentheses.withTree(result).

Use reduce for searches inside a tree

To ask "does this subtree contain X", pass the accumulator as the visitor's parameter and call reduce, rather than capturing a holder and calling visitNonNull followed by .get():

// BAD
AtomicBoolean found = new AtomicBoolean();
new JavaIsoVisitor<Integer>() { /* sets found */ }.visitNonNull(tree, 0, new Cursor(getCursor(), tree));
return found.get();

// GOOD
return new JavaIsoVisitor<AtomicBoolean>() {
    @Override
    public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, AtomicBoolean found) {
        if (MATCHER.matches(method)) {
            found.set(true);
        }
        return super.visitMethodInvocation(method, found);
    }
}.reduce(tree, new AtomicBoolean()).get();

Pass a cursor (reduce(tree, acc, cursor)) only when the inner visitor reads getCursor(). Don't build Cursor chains by hand for visitors that never read them.

Use preconditions instead of tracking skipped trees

To exclude whole source files, wrap the edit visitor in a precondition instead of having the scanner record ids of files to skip:

// BAD: scanner collects UUIDs into skippedCompilationUnits; the visitor checks the set

// GOOD
return Preconditions.check(Preconditions.not(new DeclaresMethod<>(RUN_MATCHER)), new EditVisitor());

Keep a comment explaining why those files are excluded.

ScanningRecipe Accumulators

Keep the accumulator simple and skip ambiguous cases

Prefer keying the accumulator globally (for example by fully qualified name) and treating anything ambiguous, such as a name declared in more than one module, as "don't change". Skipping a rare case is cheaper than per-project ownership logic that maintainers must reason through.

Watch the per-file cost of getVisitor

Derive sets from the accumulator once, not inside the per-file visitor. A loop over accumulator entries per compilation unit, especially one that also walks every project, costs files × entries × projects and gets slow on large multi-module repositories.

Keep the scanner consistent with the edit visitor

The scanner's idea of what will change must match what the edit visitor actually reaches. If the scanner marks a declaration removable but the edit visitor never descends into its enclosing class, callers get rewritten against a declaration that still exists unchanged.

Unsafe Cases

Mark what you can't migrate instead of guessing

When a case can't be migrated safely, leave it unchanged and add a SearchResult marker explaining why. A visible marker beats a silently wrong rewrite.

Don't move a failure from compile time to run time

Check what a partial migration leaves behind. Code that used to fail to compile but now compiles and fails at run time (for example a test class JUnit can no longer instantiate) is harder to spot in a large migration. Either finish the change or leave something both callers and the framework can use.

Recipe Metadata

Include RSPEC tags for SonarQube rules

@Override
public Set<String> getTags() {
    return Collections.singleton("RSPEC-S3020");
}

Use the SonarQube time estimate

@Override
public Duration getEstimatedEffortPerOccurrence() {
    return Duration.ofMinutes(2);
}

YAML Configuration

Add new recipes to recipe collections

recipeList:
    - org.openrewrite.staticanalysis.CollectionToArrayShouldHaveProperType

Common collections:

  • common-static-analysis.yml - General static analysis fixes
  • java-best-practices.yml - Java-specific best practices
  • static-analysis.yml - Broader static analysis recipes

At-Scale Validation

Before submitting, run recipes at scale against large codebases (e.g., the Spring or Netflix orgs). This catches bugs unit tests miss:

  • Inherited members being incorrectly qualified (e.g., SuperClass.this.method() instead of this.method())
  • Recipes accidentally modifying Kotlin files (see Language Scoping above)

Code Style

  • Explicit imports over wildcards (java.util.List not java.util.*)
  • Static imports for Collections.emptyList() and singletonList()
  • @Nullable from org.jspecify.annotations on methods that can return null
  • Don't add @NonNull on parameters (non-null is the default)
  • Inline small single-use helper methods rather than creating many tiny private methods
  • Ternary for simple conditional returns
  • Pass pre-validated/cast values as parameters rather than re-checking inside helper methods

Recipe Tests

Import ordering failures

Recipe tests often fail on import order alone, not on the transformation:

-import java.util.List;
-import org.assertj.core.api.Assertions;
+import org.assertj.core.api.Assertions;
+import java.util.List;

If imports are missing entirely, fix the recipe: declare them on the JavaTemplate and call maybeAddImport / maybeRemoveImport, as described under JavaTemplate Usage above.

If only the order differs, accept the order OpenRewrite produces rather than forcing your own: copy the actual output from the failure into the expected text, confirm the transformation itself is right, and rerun. OpenRewrite typically orders imports as third-party packages, blank line, java.* / javax.*, then static imports after another blank line.

"""
import org.assertj.core.api.Assertions;
import org.eclipse.collections.impl.utility.Iterate;

import java.util.List;
"""

The ~~> prefix ("ignore everything before this line") is not recognized in every codebase. If it fails, remove it and match exactly.

Type validation

For tests with custom types that lack complete type information, prefer types that exist on the classpath. Disable validation only as a last resort:

rewriteRun(
  spec -> spec.typeValidationOptions(TypeValidation.none()),
  java(...)
);

IDE warnings

Test inputs contain intentional issues. Suppress the resulting IDE warnings with @SuppressWarnings on the test method, or on the class when several tests share it. Common values: "RedundantCast", "ConstantConditions", "unused", "unchecked".

Language comments

Add //language=java for IDE highlighting. With a plain java("before", "after") call, put it before java. With a spec customization or several java() calls, put it on the individual strings.

Do not add //language=java to JavaTemplate strings containing #{any()} or #{}; they are not valid Java.

One scenario per test

Write one test method per scenario, not one test with dozens of sources or a parameterized test over several fixtures. Each test then has one reason to pass, a failure points at the case that broke, and no source passes for the wrong reason. Group related scenarios in a @Nested class, and tag a reproducer from an issue with @Issue.

Place new tests after the @DocumentExample test.

Don't cap cycles to hide a non-idempotent visitor

Avoid withMaxCycles(1) to make a test pass. Make the visitor stop once its change is done (for example by matching its own output) and let the default cycles run, which also exercises the second cycle, where markers added in the first are already present.

Assert types, not only text

When a change affects type attribution, assert the resulting types in afterRecipe, for example by collecting getMethodType() and argument types with a visitor's reduce and comparing them with containsExactly.

Coverage

Cover basic cases, edge cases (custom types, fully qualified types), cases where the recipe must not change anything, import handling, and formatting preservation. Cover every branch of new code, including fallbacks.

Probe the shapes that commonly break recipes:

  • Anonymous subclasses: new Foo(x) {} carries the anonymous class's constructor type, not Foo's
  • Classes nested inside classes the visitor skips
  • Callers in other source files, including non-Java (Kotlin) sources
  • Arguments that are constants, side-effecting expressions, lambdas, or method references
  • Calls left dangling after a change, such as super() once a base constructor loses its arguments

Pull Requests

Call out incidental fixes in the description

When a PR also fixes something on the side, such as a guard that stops the recipe from damaging Kotlin files, mention it in the description so it shows up in the release notes.

Maven POM Dependency Ordering

Running the check

Check the pom.xml files with local modifications (git status --porcelain -- '*pom.xml'), or all of them when none are modified. Report every violation, naming the file and the out-of-place dependency.

Ordering Rules

Group dependencies by scope (compile, runtime, test), then within each scope by groupId in this order, top to bottom:

  • First-party (${project.groupId} or modules within the project)
  • cool.klass
  • io.liftwizard
  • org.eclipse.collections
  • io.dropwizard
  • Other third-party libraries
  • Jakarta

Region Comment Structure

Use region comments for each groupId+scope combination:

  • <!--region Project compile dependencies -->
  • <!--region Project runtime dependencies -->
  • <!--region Klass compile dependencies -->
  • <!--region Klass runtime dependencies -->
  • <!--region Liftwizard compile dependencies -->
  • <!--region Liftwizard runtime dependencies -->
  • <!--region Compile dependencies --> (for other dependencies)
  • <!--region Runtime dependencies -->
  • <!--region Test dependencies -->

Close each region with <!--endregion [name] -->

Nested regions within some groups:

  • For io.liftwizard runtime: <!--region Liftwizard bundles --> then <!--region Liftwizard config-->
  • For io.dropwizard: core modules first, then specialized modules

Example Structure

<dependencies>

    <!--region Project compile dependencies -->
    <dependency>
        <groupId>${project.groupId}</groupId>
        <artifactId>example-services</artifactId>
        <version>${project.version}</version>
    </dependency>
    <!--endregion-->

    <!--region Project runtime dependencies -->
    <dependency>
        <groupId>${project.groupId}</groupId>
        <artifactId>example-domain-model</artifactId>
        <version>${project.version}</version>
        <scope>runtime</scope>
    </dependency>
    <!--endregion-->

    <!--region Liftwizard runtime dependencies -->
    <dependency>
        <groupId>io.liftwizard</groupId>
        <artifactId>liftwizard-graphql-reladomo-meta</artifactId>
        <scope>runtime</scope>
    </dependency>

    <!--region Liftwizard bundles -->
    <dependency>
        <groupId>io.liftwizard</groupId>
        <artifactId>liftwizard-bundle-cors</artifactId>
        <scope>runtime</scope>
    </dependency>
    <!--endregion-->

    <!--region Liftwizard config-->
    <dependency>
        <groupId>io.liftwizard</groupId>
        <artifactId>liftwizard-config-logging-logstash-console</artifactId>
        <scope>runtime</scope>
    </dependency>
    <!--endregion-->
    <!--endregion-->

    <!--region Test dependencies -->
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter</artifactId>
        <scope>test</scope>
    </dependency>
    <!--endregion-->

</dependencies>

Sponsors

Details

Marketplace
motlin/claude-code-plugins
Source
plugins/java
Author
Craig Motlin
Category
Productivity

More from motlin/claude-code-plugins

All 30