In this guide we'll look at using OpenRewrite to perform an automated remediation for many issues identified by common static analysis tools.
The Common Static Analysis Recipe consists of more than 50 types of issues and can be applied by including OpenRewrite's plug-in to your project and configuring the recipe:
{% tabs %} {% tab title="Maven" %} {% code title="pom.xml" %}
<plugin>
<groupId>org.openrewrite.maven</groupId>
<artifactId>rewrite-maven-plugin</artifactId>
<version>5.2.4</version>
<configuration>
<activeRecipes>
<recipe>org.openrewrite.java.cleanup.CommonStaticAnalysis</recipe>
</activeRecipes>
</configuration>
</plugin>
{% endcode %} {% endtab %}
{% tab title="Gradle" %} {% code title="build.gradle" %}
plugins {
id("java")
id("org.openrewrite.rewrite") version("6.1.8")
}
rewrite {
activeRecipe("org.openrewrite.java.cleanup.CommonStaticAnalysis")
}
repositories {
mavenCentral() // rewrite is published to Maven Central
}
{% endcode %} {% endtab %} {% endtabs %}
At this point, you're ready to fix common static analysis issues by running mvn rewrite:run
or gradlew rewriteRun
.
For the full list of changes this recipe will make, see its reference page.
{% tabs %} {% tab title="Before" %}
queue.findAll().forEach(msg -> {
WebSocketMessageBody toSend = conv.fromMap(msg.getMessage(), WebSocketMessageBody.class);
session.sendSync(toSend);
});
{% endtab %}
{% tab title="After" %}
queue.findAll().forEach((MessageQueue msg) -> {
WebSocketMessageBody toSend = conv.fromMap(msg.getMessage(), WebSocketMessageBody.class);
session.sendSync(toSend);
});
{% endtab %} {% endtabs %}
{% tabs %} {% tab title="Before" %}
class Menu {
static final List<String> menuItems = Arrays.asList("rice", "beans");
void newOrder(String main, String desert) {
List<String> menuItems = new ArrayList<>() {
{
add(main);
add(desert);
}
};
...
}
}
{% endtab %}
{% tab title="After" %}
class Menu {
static final List<String> menuItems;
static {
menuItems = new ArrayList<>();
menuItems.add("rice");
menuItems.add("beans");
}
void newOrder(String main, String desert) {
List<String> menuItems = new ArrayList<>();
menuItems.add(main);
menuItems.add(desert);
...
}
}
{% endtab %} {% endtabs %}
{% tabs %} {% tab title="Before" %}
public class MessageExtBatch implements Serializable {
private ByteBuffer encodedBuff;
...
}
{% endtab %}
{% tab title="After" %}
public class MessageExtBatch implements Serializable {
private transient ByteBuffer encodedBuff;
...
}
{% endtab %} {% endtabs %}
We don't have OpenRewrite recipes implemented for all publicly available policies. If you find a violation you'd like automated, visit the rewrite repository and file an issue.