Giter Club home page Giter Club logo

impsort-maven-plugin's Introduction

impsort-maven-plugin's People

Contributors

a14n avatar bedlaj avatar bruce-y avatar cstamas avatar ctubbsii avatar dependabot[bot] avatar dwalluck avatar gastaldi avatar gnodet avatar hazendaz avatar janscheible avatar mureinik avatar rgolangh avatar tommythorsen avatar wetneb avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

impsort-maven-plugin's Issues

JavaParser broken with Sequential Collections (jdk 21) and generally jdk 19+

Nothing to do here, just noting for others as underlying javaparser is blocking on newer jdks.

At the moment, javaparser has stated won't fix but checking on my commit to see if that might be a path forward. The issue surfaces if code is targeted to jdk 21 runtime. If it is targeted earlier it will in fact build up through 17. Anything higher has issues as blocking due to another issue with enum support locked in javaparser. I have a fix for that too that stubs that out for them. I've tested my fixes against this plugin and it works fine.

The issues found there seem to imply it works through java 20 but not exactly. The enums are needed there for its matching which is a trivial effort.

Imports are wrongly flagged as unused and removed

This is a bit of a corner case, but the input file is here and the 2 imports are removed.

@XmlSchema(
    xmlns = { 
        @XmlNs(prefix = "order", namespaceURI = "http://www.camel.apache.org/jaxb/example/order/1"),
        @XmlNs(prefix = "address", namespaceURI = "http://www.camel.apache.org/jaxb/example/address/1")
        }
)
package org.apache.camel.example;

import javax.xml.bind.annotation.XmlNs;
import javax.xml.bind.annotation.XmlSchema;

Failure to parse some files containing certain reserved keywords

impsort-maven-plugin fails when the keyword "permits" is seen as a variable name

Saw this in 1.9.0, does not appear in 1.8.0.

Upstream issue: javaparser/javaparser#4016

[INFO] --- impsort:1.9.0:sort (sort-imports) @ accumulo-core ---
(line 55,col 23) Parse error. Found "permits", expected one of  "..." "@" "enum" "exports" "module" "open" "opens" "provides" "record" "requires" "strictfp" "to" "transitive" "uses" "with" "yield" <IDENTIFIER>
Problem stacktrace : 
  com.github.javaparser.GeneratedJavaParser.generateParseException(GeneratedJavaParser.java:13933)
  com.github.javaparser.GeneratedJavaParser.jj_consume_token(GeneratedJavaParser.java:13778)
  com.github.javaparser.GeneratedJavaParser.Identifier(GeneratedJavaParser.java:3475)
  com.github.javaparser.GeneratedJavaParser.SimpleName(GeneratedJavaParser.java:3373)
  com.github.javaparser.GeneratedJavaParser.VariableDeclaratorId(GeneratedJavaParser.java:1894)
  com.github.javaparser.GeneratedJavaParser.Parameter(GeneratedJavaParser.java:2485)
  com.github.javaparser.GeneratedJavaParser.Parameters(GeneratedJavaParser.java:2312)
  com.github.javaparser.GeneratedJavaParser.MethodDeclaration(GeneratedJavaParser.java:2128)
  com.github.javaparser.GeneratedJavaParser.ClassOrInterfaceBodyDeclaration(GeneratedJavaParser.java:1771)
  com.github.javaparser.GeneratedJavaParser.ClassOrInterfaceBody(GeneratedJavaParser.java:1275)
  com.github.javaparser.GeneratedJavaParser.ClassOrInterfaceDeclaration(GeneratedJavaParser.java:538)
  com.github.javaparser.GeneratedJavaParser.CompilationUnit(GeneratedJavaParser.java:156)
  com.github.javaparser.JavaParser.parse(JavaParser.java:125)
  com.github.javaparser.JavaParser.parse(JavaParser.java:305)
  net.revelc.code.impsort.ImpSort.parseFile(ImpSort.java:129)
  net.revelc.code.impsort.maven.plugin.AbstractImpSortMojo.lambda$execute$3(AbstractImpSortMojo.java:287)
  java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
  java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)

Renaming the variable works, but it's annoying.

This issue is just to track the issue upstream. It should be fixed by them, then we can bump our dependency version.

Print parse error details for java files

Is your feature request related to a problem? Please describe.
When there are errors in parseResult and parseResult.getResult() is null, impsort doesn't provide detials in log.
For example,
when there is this line in java file

String a="aa\sbb";

The plugin only provide log:

net.revelc.code.impsort.ex.ImpSortException: file: TestException1.java; reason: unable to successfully parse the Java file

Describe the solution you'd like
Add log print for parseResult.getProblems() when parseResult.getResult() is null

Describe alternatives you've considered
Add parseResult.getProblems() into message of ImpSortException.

Allow to configure plugin to be silent when nothing has changed

Is your feature request related to a problem? Please describe.

We have a bit project Apache Camel where we use this plugin to auto sort our java source code. Thanks for this plugin, its working great.

However as we have many modules and build on CI servers and whatnot, then we wade through endless of maven output.
Therefore it would be good if there was a configuration option you can turn on, that will make this plugin silent or output less when there was nothing changed.

For example

[INFO] --- impsort-maven-plugin:1.4.1:sort (sort-imports) @ camel-netty-http ---
[INFO]  Total Files Processed: 188 in 00:01.307
[INFO]         Already Sorted: 188
[INFO]         Needed Sorting:   0

Could be outputted as (true)

[INFO] --- impsort-maven-plugin:1.4.1:sort (sort-imports) @ camel-netty-http ---
[INFO]  Total Files Processed: 188 in 00:01.307 (Needed sorting: 0)

Or even more silent

[INFO] --- impsort-maven-plugin:1.4.1:sort (sort-imports) @ camel-netty-http ---

And then only if there was some updates it would output

[INFO] --- impsort-maven-plugin:1.4.1:sort (sort-imports) @ camel-netty-http ---
[INFO]  Total Files Processed: 188 in 00:01.521
[INFO]         Already Sorted: 184
[INFO]         Needed Sorting:   4

Prevent import from being removed if it is shadowing a type in the `java.lang` package

The treatSamePackageAsUnused feature will remove imports for types in the same package as the compilation unit.

However, it may be necessary to keep some of these import statements, in order for the package-local type to shadow a type of the same simple name in the java.lang package. For example, in JDK14, there may be a class in the same package called Record. Removing the explicit import statement will cause java.lang.Record to be used instead of the package-local type that the explicit import statement intended.

I can think of a few mitigations for this:

  1. Keep the package-local import statement if a type, n, exists as java.lang.n (the problem with this is we can only check the build-time JDK, not the target JDK the code is being compiled for, without a lot of extra configuration and pre-defined JDK target signatures, so it could still be overly aggressive),
  2. Add a plugin configuration option to exclude properties from automatic removal, by name (or pattern), or
  3. Add a comment-parsing option so specific imports can be annotated inline in the code to always keep specific imports.

Possible EOL issue

Running the check goal it is failing on the same file over and over. My team is has a current mix of OS's Windows and Apple. For that reason we are using 'LF' line endings.

The Imports

import java.util.Arrays;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;

import com.google.common.base.Stopwatch;

The plugin config

<plugin>
    <groupId>net.revelc.code</groupId>
    <artifactId>impsort-maven-plugin</artifactId>
    <executions>
        <execution>
            <phase>validate</phase>
            <goals>
                <goal>check</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <groups>java.,javax.,org.,com.</groups>
        <staticGroups>java,*</staticGroups>
    </configuration>
</plugin>

any ideas on why it is failing? I took out the blank lines, and it still failed on goal execution.

Thanks,

allow avoiding empty line between groups

I'd like to configure import order that matches what IntelliJ IDEA does (in its default configuration). That is:

import "all other imports"
<blank line>
import javax.*
import java.*
<blank line>
import static "all other imports"

I got very close by using this configuration:

<configuration>
    <groups>*,javax.,java.</groups>
    <staticGroups>*</staticGroups>
    <staticAfter>true</staticAfter>
    <removeUnused>true</removeUnused>
</configuration>

However, this creates an empty line between the javax. and java. groups. One last thing to avoid! :-)

The configuration might just use a different separator to mean "two different groups, but no empty line". Something like *,javax.+java..

WDYT? I can try implementing this, if you think it's worth it.

removeUnused feature in #6 should not remove imports used by javadoc

Currently, the removeUnused feature added in #6 removes any unused imports, as determined by checking identifier tokens in Java code. However, import statements are also used by javadocs to shorten @see and @link javadoc tags.

The current implementation is too overly aggressive at removing unused imports. Imports used by javadocs should still be considered in-use.

An example project I noticed this on was: https://github.com/apache/accumulo, which contains a lot of javadocs.

NPE while sorting imports using v1.4.1

[ERROR] Failed to execute goal net.revelc.code:impsort-maven-plugin:1.4.1:sort (default-cli) on project SbiComCnPat: Execution default-cli of goal net.revelc.code:impsort-maven-plugin:1.4.1:sort failed.: NullPointerException -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal net.revelc.code:impsort-maven-plugin:1.4.1:sort (default-cli) on project SbiComCnPat: Execution default-cli of goal net.revelc.code:impsort-maven-plugin:1.4.1:sort failed.
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:215)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.builder.multithreaded.MultiThreadedBuilder$1.call (MultiThreadedBuilder.java:190)
    at org.apache.maven.lifecycle.internal.builder.multithreaded.MultiThreadedBuilder$1.call (MultiThreadedBuilder.java:186)
    at java.util.concurrent.FutureTask.run (FutureTask.java:266)
    at java.util.concurrent.Executors$RunnableAdapter.call (Executors.java:511)
    at java.util.concurrent.FutureTask.run (FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:624)
    at java.lang.Thread.run (Thread.java:748)
Caused by: org.apache.maven.plugin.PluginExecutionException: Execution default-cli of goal net.revelc.code:impsort-maven-plugin:1.4.1:sort failed.
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:148)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:210)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.builder.multithreaded.MultiThreadedBuilder$1.call (MultiThreadedBuilder.java:190)
    at org.apache.maven.lifecycle.internal.builder.multithreaded.MultiThreadedBuilder$1.call (MultiThreadedBuilder.java:186)
    at java.util.concurrent.FutureTask.run (FutureTask.java:266)
    at java.util.concurrent.Executors$RunnableAdapter.call (Executors.java:511)
    at java.util.concurrent.FutureTask.run (FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:624)
    at java.lang.Thread.run (Thread.java:748)
Caused by: java.lang.NullPointerException
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0 (Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance (NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance (DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance (Constructor.java:423)
    at java.util.concurrent.ForkJoinTask.getThrowableException (ForkJoinTask.java:598)
    at java.util.concurrent.ForkJoinTask.reportException (ForkJoinTask.java:677)
    at java.util.concurrent.ForkJoinTask.invoke (ForkJoinTask.java:735)
    at java.util.stream.ReduceOps$ReduceOp.evaluateParallel (ReduceOps.java:714)
    at java.util.stream.AbstractPipeline.evaluate (AbstractPipeline.java:233)
    at java.util.stream.ReferencePipeline.reduce (ReferencePipeline.java:546)
    at net.revelc.code.impsort.maven.plugin.AbstractImpSortMojo.execute (AbstractImpSortMojo.java:251)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:137)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:210)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.builder.multithreaded.MultiThreadedBuilder$1.call (MultiThreadedBuilder.java:190)
    at org.apache.maven.lifecycle.internal.builder.multithreaded.MultiThreadedBuilder$1.call (MultiThreadedBuilder.java:186)
    at java.util.concurrent.FutureTask.run (FutureTask.java:266)
    at java.util.concurrent.Executors$RunnableAdapter.call (Executors.java:511)
    at java.util.concurrent.FutureTask.run (FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:624)
    at java.lang.Thread.run (Thread.java:748)
Caused by: java.lang.NullPointerException
    at java.lang.String.split (String.java:2337)
    at java.lang.String.split (String.java:2422)
    at net.revelc.code.impsort.ImpSort.parseFile (ImpSort.java:85)
    at net.revelc.code.impsort.maven.plugin.AbstractImpSortMojo.lambda$execute$3 (AbstractImpSortMojo.java:228)
    at java.util.stream.ReferencePipeline$3$1.accept (ReferencePipeline.java:193)
    at java.util.stream.ReferencePipeline$3$1.accept (ReferencePipeline.java:193)
    at java.util.stream.ForEachOps$ForEachOp$OfRef.accept (ForEachOps.java:183)
    at java.util.stream.ReferencePipeline$3$1.accept (ReferencePipeline.java:193)
    at java.util.Spliterators$ArraySpliterator.forEachRemaining (Spliterators.java:948)
    at java.util.stream.AbstractPipeline.copyInto (AbstractPipeline.java:482)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto (AbstractPipeline.java:472)
    at java.util.stream.ForEachOps$ForEachOp.evaluateSequential (ForEachOps.java:150)
    at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential (ForEachOps.java:173)
    at java.util.stream.AbstractPipeline.evaluate (AbstractPipeline.java:234)
    at java.util.stream.ReferencePipeline.forEach (ReferencePipeline.java:485)
    at java.util.stream.ReferencePipeline$7$1.accept (ReferencePipeline.java:272)
    at java.util.Spliterators$ArraySpliterator.forEachRemaining (Spliterators.java:948)
    at java.util.stream.AbstractPipeline.copyInto (AbstractPipeline.java:482)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto (AbstractPipeline.java:472)
    at java.util.stream.ReduceOps$ReduceTask.doLeaf (ReduceOps.java:747)
    at java.util.stream.ReduceOps$ReduceTask.doLeaf (ReduceOps.java:721)
    at java.util.stream.AbstractTask.compute (AbstractTask.java:327)
    at java.util.concurrent.CountedCompleter.exec (CountedCompleter.java:731)
    at java.util.concurrent.ForkJoinTask.doExec (ForkJoinTask.java:289)
    at java.util.concurrent.ForkJoinPool$WorkQueue.runTask (ForkJoinPool.java:1056)
    at java.util.concurrent.ForkJoinPool.runWorker (ForkJoinPool.java:1692)
    at java.util.concurrent.ForkJoinWorkerThread.run (ForkJoinWorkerThread.java:157)

[Feature] Make includes work with `src/generated`

Is your feature request related to a problem? Please describe.
Just this morning I tried to us the maven plugin to format our src/generated/java code but noticed that it was completely skipped when running the maven plugin.

For our project we check in the src/generated/java folder and all of the code inside of it since it generated from an openAPI specification and want to remove all unused imports that the openAPI generate creates.

Describe the solution you'd like
Make it possible to add src/generated/java as a valid path

Describe alternatives you've considered
None

Additional context
None

imp sort fail on windows 10

Describe the bug
when I run the mvn process-sources, I get an error on file because of line ending. If I delete few line it work again.

Failed to execute goal net.revelc.code:impsort-maven-plugin:1.4.1:sort (sort-imports) on project quarkus-cxf-deployment: Error reading file D:\src\quarkiverse-cxf\deployment\src\main\java\io\quarkiverse\cxf\deployment\QuarkusCxfProcessor.java: Unable to parse D:\src\quarkiverse-cxf\deployment\src\main\java\io\quarkiverse\cxf\deployment\QuarkusCxfProcessor.java

issue is on file :
https://github.com/quarkiverse/quarkiverse-cxf/blob/master/deployment/src/main/java/io/quarkiverse/cxf/deployment/QuarkusCxfProcessor.java
if I remove line 1425 to 1520
it work again.

Versions (OS, Maven, Java, and others, as appropriate):

  • Affected version(s) of this project: 1.4.1
    Apache Maven 3.6.2 (40f52333136460af0dc0d7232c0dc0bcf0d9e117; 2019-08-27T17:06:16+02:00)
    Java version: 1.8.0_221, vendor: Oracle Corporation, runtime: C:\Program Files\Java\jdk1.8.0_221\jre
    Default locale: fr_FR, platform encoding: Cp1252
    OS name: "windows 10", version: "10.0", arch: "amd64", family: "windows"

To Reproduce
Steps to reproduce the behavior (or a link to an example repository that reproduces the problem):

  1. git clone https://github.com/quarkiverse/quarkiverse-cxf.git
  2. run mvn process-sources
  3. see error

Expected behavior
import sorted and no error.

Parse error for `sealed` classes

First of all, thank you all for your work on this plugin.

Describe the bug

Keywords sealed and non-sealed are not recognized even settingcompliance property to 17.

Versions (OS, Maven, Java, and others, as appropriate):

  • Affected version(s) of this project: 1.6.2
  • OS: Windows (but I suppose it's OS independent)
  • Maven version:
Apache Maven 3.8.2 (ea98e05a04480131370aa0c110b8c54cf726c06f)
Maven home: c:\opt\maven
Java version: 17, vendor: Oracle Corporation, runtime: c:\opt\jdk
Default locale: it_IT, platform encoding: Cp1252
OS name: "windows 10", version: "10.0", arch: "amd64", family: "windows"

To Reproduce

Add a sealed/non-sealed class to any project using Impsort plugin.

Es:

package test;

import java.io.IOException;

public sealed class Foo extends IOException permits Bar {
}

non-sealed class Bar extends Foo {
}

Expected behavior

Imports are sorted with no error

Screenshots

Plugin configuration (note compliance 17, I've tried setting impsort.compliance in general properties too):

<plugin>
  <groupId>net.revelc.code</groupId>
  <artifactId>impsort-maven-plugin</artifactId>
  <version>1.6.2</version>
  <configuration>
    <removeUnused>true</removeUnused>
    <lineEnding>LF</lineEnding>
    <groups>java.,javax.,com.,org.,it.,eu.</groups>
    <staticGroups>java.,javax.,com.,org.,it.,eu.</staticGroups>
    <compliance>17</compliance>
  </configuration>
</plugin>

Stacktrace:

[INFO] --- impsort-maven-plugin:1.6.2:sort (fmt-repair-imports) @ test-proj ---
(line 3,col 1) Parse error. Found  "sealed" <IDENTIFIER>, expected one of  ";" "@" "class" "enum" "interface" "module" "open" "record"
Problem stacktrace :
  com.github.javaparser.GeneratedJavaParser.generateParseException(GeneratedJavaParser.java:13717)
  com.github.javaparser.GeneratedJavaParser.jj_consume_token(GeneratedJavaParser.java:13563)
  com.github.javaparser.GeneratedJavaParser.CompilationUnit(GeneratedJavaParser.java:182)
  com.github.javaparser.JavaParser.parse(JavaParser.java:123)
  com.github.javaparser.JavaParser.parse(JavaParser.java:306)
  net.revelc.code.impsort.ImpSort.parseFile(ImpSort.java:128)
  net.revelc.code.impsort.maven.plugin.AbstractImpSortMojo.lambda$execute$3(AbstractImpSortMojo.java:287)
  java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197)
  java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197)
  java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:183)
  java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197)
  java.base/java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:992)
  java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:509)
  java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:499)
  java.base/java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150)
  java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173)
  java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
  java.base/java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:596)
  java.base/java.util.stream.ReferencePipeline$7$1.accept(ReferencePipeline.java:276)
  java.base/java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:992)
  java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:509)
  java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:499)
  java.base/java.util.stream.ReduceOps$ReduceTask.doLeaf(ReduceOps.java:960)
  java.base/java.util.stream.ReduceOps$ReduceTask.doLeaf(ReduceOps.java:934)
  java.base/java.util.stream.AbstractTask.compute(AbstractTask.java:327)
  java.base/java.util.concurrent.CountedCompleter.exec(CountedCompleter.java:754)
  java.base/java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:373)
  java.base/java.util.concurrent.ForkJoinPool$WorkQueue.topLevelExec(ForkJoinPool.java:1182)
  java.base/java.util.concurrent.ForkJoinPool.scan(ForkJoinPool.java:1655)
  java.base/java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1622)
  java.base/java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:165)
[INFO] Processed 10 files in 00:00.406 (Already Sorted: 7, Needed Sorting: 3)
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  2.688 s
[INFO] Finished at: 2021-10-25T11:30:42+02:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal net.revelc.code:impsort-maven-plugin:1.6.2:sort (fmt-repair-imports) on project test-proj: Error reading file C:\Users\****\src\main\java\test\Foo.java: file: C:\Users\****\src\main\java\test\Foo.java; reason: the Java file contained parse errors -> [Help 1]
[ERROR]

Parsing error when java file contains variable named `permits`

Describe the bug

After upgrading from version 1.8.0 to 1.9.0, when a variable in a file is named permits, the plugin execution fails on a parsing error.

Versions (OS, Maven, Java, and others, as appropriate):

  • Affected version(s) of this project: 1.9.0
mvn --version
Apache Maven 3.8.6 (84538c9988a25aec085021c365c560670ad80f63)
Maven home: /home/nec/.sdkman/candidates/maven/current
Java version: 11.0.20, vendor: Eclipse Adoptium, runtime: /home/nec/.sdkman/candidates/java/11.0.20-tem
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "6.2.0-35-generic", arch: "amd64", family: "unix"

To Reproduce
Steps to reproduce the behavior:

  1. Create a file:
package mypackage.mypackage

import java.util.concurrent.atomic.AtomicInteger;

public class TestPermitKeyword {

	void testPermitKeyWord() {
		final AtomicInteger permits = new AtomicInteger(0);
	}

}
  1. Run command : mvn -DskipTests -Dcheckstyle.skip impsort:sort@sort-imports
  2. Error is:
[ERROR] Failed to execute goal net.revelc.code:impsort-maven-plugin:1.9.0:sort (sort-imports) on project myProject: Error reading file /home/path/to/myProject/path/to/file/TestPermitKeyword.java: file: /home/path/to/myProject/path/to/file/TestPermitKeyword.java; reason: the Java file contained parse errors
  1. Workaround: rename variable permits to nPermits

Expected behavior
No parse error

Textblock in the javacode makes the maven build fail

Describe the bug
If we have a class like the following with a textblock

import org.junit.jupiter.api.Test;

public class TextBlockTestCase {

    @Test
    public void hello() {
        String s = """
                hello world
                """;
    }
}

and run mvn process-sources it fails with

[ERROR] Failed to execute goal net.revelc.code:impsort-maven-plugin:1.6.0:sort (sort-imports) on project nettskjema-api: Error reading file /MyPath/TextBlockTestCase.java: file: /MyPath/TextBlockTestCase.java; reason: the Java file contained parse errors -> [Help 1]

Versions (OS, Maven, Java, and others, as appropriate):

  • impsort-maven-plugin 1.6.0

To Reproduce
Steps to reproduce the behavior (or a link to an example repository that reproduces the problem):

  1. Create a class with a textblock like the one described above
  2. Run mvn process-sources

Expected behavior
No errors

Impsort duplicates comments above first import if there is no space separation

Describe the bug
When there is a comment before the first import and there is not a space between the comment and the import line.
When running impsort, this comment is duplicated.

Versions (OS, Maven, Java, and others, as appropriate):

  • Affected version(s) of this project: 1.4.1
  • OS: MacOS

To Reproduce
Steps to reproduce the behavior (or a link to an example repository that reproduces the problem):

  1. Write any Java file with any imports .
  2. Write a comment above the first import.
// some comment
import foo.bar;
import bar.baz;

class Foo(){
}
  1. Run impsort on the file.
  2. See duplicated comment.
// some comment

// some comment
import foo.bar;
import bar.baz;

class Foo(){
}

Expected behavior
This comment is moved around with the import but not duplicated.

Additional context
This also is an issue with block comments, where the entire block comment is duplicated. In the Maven Debug logs, we see the log that it Found imports: with the comment included above the import line.

<removeUnused>true</removeUnused> is not apply to imports

I have this class : import java.applet.*; is not used

package org.acme.neo4j;

import java.applet.*;

import org.neo4j.driver.types.Node;

public class Fruit {

    public Long id;

    public String name;

    public static Fruit from(Node node) {
        return new Fruit(node.id(), node.get("name").asString());
    }

    public Fruit() {
        // This is neaded for the REST-Easy JSON Binding
    }

    public Fruit(String name) {
        this.name = name;
    }

    public Fruit(Long id, String name) {
        this.id = id;
        this.name = name;
    }
}

When I do : mvn compile

I obtain this :

[INFO] --- impsort-maven-plugin:1.4.1:sort (sort-imports) @ neo4j-java ---
[INFO]  Total Files Processed: 8 in 00:00.341
[INFO]         Already Sorted: 8
[INFO]         Needed Sorting: 0
[INFO]

here my config in pom.xml

<plugin>
        <groupId>net.revelc.code</groupId>
        <artifactId>impsort-maven-plugin</artifactId>
        <executions>
          <execution>
            <id>sort-imports</id>
            <goals>
              <goal>sort</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <groups>java.,javax.,org.,com.</groups>
          <staticGroups>java,*</staticGroups>
          <removeUnused>true</removeUnused>
        </configuration>
      </plugin>

Allow ASCII sort order for static imports

Greetings,
First of all, thanks for your work in this plugin, I've been using it regularly and it's very useful and time saving.

However, I've noticed the static import order is not fully compliant with the Google Java style that our organization wishes to enforce, which is based in ASCII sort order. This raises some issues when pairing this plugin with certain Checkstyle configurations.

Basically, according to ASCII Sort order, imports starting with capital letters are expected to be placed first.

Currently, ImpSort sort order returns this:
non-ascii

While Ascii Sort order would produce:
ascii

This results in unavoidable checkstyle violations in projects whose checkstyle sheets include:
<property name="sortImportsInGroupAlphabetically" value="true"/>

Is there any chance we get a param to toogle Ascii Sort Order?

Thanks in advance.

A required class was missing while executing net.revelc.code:impsort-maven-plugin:1.5.0:sort: org/codehaus/plexus/util/DirectoryScanner

Describe the bug
[INFO] --- impsort:1.5.0:sort (default) @ process-usertasks-quarkus-with-console ---
[INFO] Using compiler compliance level: JAVA_11
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 34.941 s
[INFO] Finished at: 2023-02-21T14:12:13+08:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal net.revelc.code:impsort-maven-plugin:1.5.0:sort (default) on project process-usertasks-quarkus-with-console: Execution default of goal net.revelc.code:impsort-maven-plugin:1.5.0:sort failed: A required class was missing while executing net.revelc.code:impsort-maven-plugin:1.5.0:sort: org/codehaus/plexus/util/DirectoryScanner
[ERROR] -----------------------------------------------------
[ERROR] realm = plugin>net.revelc.code:impsort-maven-plugin:1.5.0
[ERROR] strategy = org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy
[ERROR] urls[0] = file:/root/.m2/repository/net/revelc/code/impsort-maven-plugin/1.5.0/impsort-maven-plugin-1.5.0.jar
[ERROR] urls[1] = file:/root/.m2/repository/com/github/javaparser/javaparser-core/3.18.0/javaparser-core-3.18.0.jar
[ERROR] Number of foreign imports: 1
[ERROR] import: Entry[import from realm ClassRealm[project>org.kie.kogito.examples:process-usertasks-quarkus-with-console:1.34.0.Final, parent: ClassRealm[maven.api, parent: null]]]
[ERROR]
[ERROR] -----------------------------------------------------
[ERROR] : org.codehaus.plexus.util.DirectoryScanner
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginContainerException

Versions (OS, Maven, Java, and others, as appropriate):

  • Affected version(s) of this project: [e.g. 1.10.0]
  • OS: [e.g. CentOS 7.5]
  • Others:

To Reproduce
Steps to reproduce the behavior (or a link to an example repository that reproduces the problem):

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots
If applicable, add screenshots to help explain your problem.

Additional context
Add any other context about the problem here.

Cache is not invalidated/recalculated on plugin update

Describe the bug
Cache is not invalidated on plugin update.

Versions (OS, Maven, Java, and others, as appropriate):

  • 1.6.0/1.6.1
  • OS: Ubuntu 20
  • Others: Maven 3.8.1, Java 11.0.11 (AdoptOpenJDK)

To Reproduce
Steps to reproduce the behavior (or a link to an example repository that reproduces the problem):

  1. Optional: Set e.g. <cachedir>.cache</cachedir> (outside of target). If you don't do this make sure to not use mvn clean ... for obvious reasons.
  2. Run the plugin in version 1.6.0 via mvn
  3. Check file
  4. Run the plugin in version 1.6.1 via mvn
  5. Check file again, it did not change

Expected behavior
As plugin updates might alter the sorting result, the plugin version should be taken into account when calculating the hashes.

Additional context
I scanned #42 briefly and I couldn't find anything related to the plugin version or the plugin config. I do think that if you change certain config parameters, the cache should be invalidated as well.

I ran into thos problem while trying to reproduce quarkusio/quarkus#17190 locally. Since I already had a cache from a 1.6.0 run, I at first could not reproduce CI behavior.

Enhance impsort:check to detect * imports

* imports are bad practice from various reasons

impsort:check could be enhanced to detect * imports

Possibly an option which is not enabled by default but can be enabled when the user wants.

Handle case where imports occur on the same line as other statements

If the first import occurs on the same line as the package statement, the package statement will get deleted.

If the last import occurs on the same line as the start of the class, the class start will get deleted.

These can be fixed by tracking where within these lines one begins and the other ends.

Plugin fails with upcoming Maven 3.9.0

Describe the bug
The impsort-maven-plugin depends on a Maven2 feature that is about to be removed in Maven 3.9,0 and Maven 4.0,0: "auto injection" of plexus-utils. In short: plugin uses but does NOT declares COMPILE dependency on plexus-utils. Maven2 was making plexus-utils "provided", while Maven 3.x supported this for backward compatilibty reasons, but Maven 3,9 and later will not.

Versions (OS, Maven, Java, and others, as appropriate):

  • Affected version(s) of this project: all
  • OS: all
  • Others:

To Reproduce

  1. build locally Maven 3.9 or 4.0 snapshot
  2. build some project using this plugin (for example maven daemon)
  3. See error
[ERROR] Failed to execute goal net.revelc.code:impsort-maven-plugin:1.7.0:sort (sort-imports) on project mvnd-build-maven-plugin: Execution sort-imports of goal net.revelc.code:impsort-maven-plugin:1.7.0:sort failed: A required class was missing while executing net.revelc.code:impsort-maven-plugin:1.7.0:sort: null
[ERROR] -----------------------------------------------------
[ERROR] realm =    plugin>net.revelc.code:impsort-maven-plugin:1.7.0
[ERROR] strategy = org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy
[ERROR] urls[0] = file:/home/cstamas/.m2/repository-oss/net/revelc/code/impsort-maven-plugin/1.7.0/impsort-maven-plugin-1.7.0.jar
[ERROR] urls[1] = file:/home/cstamas/.m2/repository-oss/com/github/javaparser/javaparser-core/3.24.2/javaparser-core-3.24.2.jar
[ERROR] urls[2] = file:/home/cstamas/.m2/repository-oss/com/google/guava/guava/31.1-jre/guava-31.1-jre.jar
[ERROR] urls[3] = file:/home/cstamas/.m2/repository-oss/com/google/guava/failureaccess/1.0.1/failureaccess-1.0.1.jar
[ERROR] urls[4] = file:/home/cstamas/.m2/repository-oss/com/google/guava/listenablefuture/9999.0-empty-to-avoid-conflict-with-guava/listenablefuture-9999.0-empty-to-avoid-conflict-with-guava.jar
[ERROR] urls[5] = file:/home/cstamas/.m2/repository-oss/com/google/code/findbugs/jsr305/3.0.2/jsr305-3.0.2.jar
[ERROR] urls[6] = file:/home/cstamas/.m2/repository-oss/org/checkerframework/checker-qual/3.12.0/checker-qual-3.12.0.jar
[ERROR] urls[7] = file:/home/cstamas/.m2/repository-oss/com/google/errorprone/error_prone_annotations/2.11.0/error_prone_annotations-2.11.0.jar
[ERROR] urls[8] = file:/home/cstamas/.m2/repository-oss/com/google/j2objc/j2objc-annotations/1.3/j2objc-annotations-1.3.jar
[ERROR] Number of foreign imports: 1
[ERROR] import: Entry[import  from realm ClassRealm[maven.api, parent: null]]
[ERROR] 
[ERROR] -----------------------------------------------------

Expected behavior
To work as before.

Sort goal fails on class containing empty javadoc

If imports needs sorting and also there is empty javadoc on class level, the plugin fails with IndexOutOfBoundsException. Tested with version 1.3.0

Class

    package some.pkg;
    
    import java.util.List;
    import java.util.ArrayList;
    
    /**
    */
    public class SomeClass {
        List something = new ArrayList();
    }

pom.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>

        <groupId>eu.janbednar</groupId>
        <artifactId>impsorttest</artifactId>
        <version>1.0-SNAPSHOT</version>

        <build>
            <plugins>
                <plugin>
                    <groupId>net.revelc.code</groupId>
                    <artifactId>impsort-maven-plugin</artifactId>
                    <version>1.3.0</version>
                    <configuration>
                        <groups>java.,javax.,org.w3c,org.xml,junit</groups>
                        <staticGroups>*</staticGroups>
                        <removeUnused>true</removeUnused>
                        <staticAfter>true</staticAfter>
                    </configuration>
                    <executions>
                        <execution>
                            <id>sort-imports</id>
                            <goals>
                                <goal>sort</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>
    </project>

mvn impsort:sort -e

> [INFO] Error stacktraces are turned on.
[INFO] Scanning for projects...
[INFO] 
[INFO] ----------------------< eu.janbednar:impsorttest >----------------------
[INFO] Building impsorttest 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO] 
[INFO] --- impsort-maven-plugin:1.3.0:sort (default-cli) @ impsorttest ---
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  1.509 s
[INFO] Finished at: 2019-11-02T16:20:30+01:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal net.revelc.code:impsort-maven-plugin:1.3.0:sort (default-cli) on project impsorttest: Execution default-cli of goal net.revelc.code:impsort-maven-plugin:1.3.0:sort failed.: IndexOutOfBoundsException: Index: 0, Size: 0 -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal net.revelc.code:impsort-maven-plugin:1.3.0:sort (default-cli) on project impsorttest: Execution default-cli of goal net.revelc.code:impsort-maven-plugin:1.3.0:sort failed.
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:215)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:956)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:288)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:192)
    at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:498)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:282)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:225)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:406)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347)
    at org.codehaus.classworlds.Launcher.main (Launcher.java:47)
Caused by: org.apache.maven.plugin.PluginExecutionException: Execution default-cli of goal net.revelc.code:impsort-maven-plugin:1.3.0:sort failed.
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:148)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:210)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:956)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:288)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:192)
    at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:498)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:282)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:225)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:406)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347)
    at org.codehaus.classworlds.Launcher.main (Launcher.java:47)
Caused by: java.lang.IndexOutOfBoundsException
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0 (Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance (NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance (DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance (Constructor.java:423)
    at java.util.concurrent.ForkJoinTask.getThrowableException (ForkJoinTask.java:598)
    at java.util.concurrent.ForkJoinTask.reportException (ForkJoinTask.java:677)
    at java.util.concurrent.ForkJoinTask.invoke (ForkJoinTask.java:735)
    at java.util.stream.ReduceOps$ReduceOp.evaluateParallel (ReduceOps.java:714)
    at java.util.stream.AbstractPipeline.evaluate (AbstractPipeline.java:233)
    at java.util.stream.ReferencePipeline.reduce (ReferencePipeline.java:479)
    at net.revelc.code.impsort.maven.plugin.AbstractImpSortMojo.execute (AbstractImpSortMojo.java:234)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:137)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:210)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:956)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:288)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:192)
    at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:498)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:282)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:225)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:406)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347)
    at org.codehaus.classworlds.Launcher.main (Launcher.java:47)
Caused by: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
    at java.util.ArrayList.rangeCheck (ArrayList.java:653)
    at java.util.ArrayList.get (ArrayList.java:429)
    at com.github.javaparser.JavadocParser.cleanLines (JavadocParser.java:124)
    at com.github.javaparser.JavadocParser.parse (JavadocParser.java:50)
    at com.github.javaparser.StaticJavaParser.parseJavadoc (StaticJavaParser.java:365)
    at com.github.javaparser.ast.comments.JavadocComment.parse (JavadocComment.java:75)
    at net.revelc.code.impsort.ImpSort.lambda$tokensInUse$8 (ImpSort.java:226)
    at java.util.stream.ReferencePipeline$3$1.accept (ReferencePipeline.java:193)
    at java.util.stream.ReferencePipeline$2$1.accept (ReferencePipeline.java:175)
    at java.util.LinkedList$LLSpliterator.forEachRemaining (LinkedList.java:1235)
    at java.util.stream.AbstractPipeline.copyInto (AbstractPipeline.java:481)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto (AbstractPipeline.java:471)
    at java.util.stream.StreamSpliterators$WrappingSpliterator.forEachRemaining (StreamSpliterators.java:312)
    at java.util.stream.Streams$ConcatSpliterator.forEachRemaining (Streams.java:743)
    at java.util.stream.AbstractPipeline.copyInto (AbstractPipeline.java:481)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto (AbstractPipeline.java:471)
    at java.util.stream.ReduceOps$ReduceOp.evaluateSequential (ReduceOps.java:708)
    at java.util.stream.AbstractPipeline.evaluate (AbstractPipeline.java:234)
    at java.util.stream.ReferencePipeline.collect (ReferencePipeline.java:499)
    at net.revelc.code.impsort.ImpSort.tokensInUse (ImpSort.java:249)
    at net.revelc.code.impsort.ImpSort.parseFile (ImpSort.java:110)
    at net.revelc.code.impsort.maven.plugin.AbstractImpSortMojo.lambda$execute$3 (AbstractImpSortMojo.java:211)
    at java.util.stream.ReferencePipeline$3$1.accept (ReferencePipeline.java:193)
    at java.util.stream.ReferencePipeline$3$1.accept (ReferencePipeline.java:193)
    at java.util.stream.ForEachOps$ForEachOp$OfRef.accept (ForEachOps.java:184)
    at java.util.stream.ReferencePipeline$3$1.accept (ReferencePipeline.java:193)
    at java.util.Spliterators$ArraySpliterator.forEachRemaining (Spliterators.java:948)
    at java.util.stream.AbstractPipeline.copyInto (AbstractPipeline.java:481)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto (AbstractPipeline.java:471)
    at java.util.stream.ForEachOps$ForEachOp.evaluateSequential (ForEachOps.java:151)
    at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential (ForEachOps.java:174)
    at java.util.stream.AbstractPipeline.evaluate (AbstractPipeline.java:234)
    at java.util.stream.ReferencePipeline.forEach (ReferencePipeline.java:418)
    at java.util.stream.ReferencePipeline$7$1.accept (ReferencePipeline.java:270)
    at java.util.Spliterators$ArraySpliterator.forEachRemaining (Spliterators.java:948)
    at java.util.stream.AbstractPipeline.copyInto (AbstractPipeline.java:481)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto (AbstractPipeline.java:471)
    at java.util.stream.ReduceOps$ReduceTask.doLeaf (ReduceOps.java:747)
    at java.util.stream.ReduceOps$ReduceTask.doLeaf (ReduceOps.java:721)
    at java.util.stream.AbstractTask.compute (AbstractTask.java:316)
    at java.util.concurrent.CountedCompleter.exec (CountedCompleter.java:731)
    at java.util.concurrent.ForkJoinTask.doExec (ForkJoinTask.java:289)
    at java.util.concurrent.ForkJoinPool$WorkQueue.runTask (ForkJoinPool.java:1056)
    at java.util.concurrent.ForkJoinPool.runWorker (ForkJoinPool.java:1692)
    at java.util.concurrent.ForkJoinWorkerThread.run (ForkJoinWorkerThread.java:157)
[ERROR] 
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR] 
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginExecutionException

Manage star imports

An issue about detecting star imports was closed because it was unnecessarily duplicating functionality already available in the checkstyle project #21

But checkstyle only complains about violations, it doesn't fix anything. With a codebase where star is already in use I would have to go and manually convert all the uses to single imports. What I am proposing is for this plugin to do that work. Just like the formatter-maven-plugin, it should ensure that the code follows a convention with respect to imports.

Intellij's configuration allows specifying a Class count to use import with '*' and a Names count to use static import with '*'
So perhaps the way to do this is define 2 parameters, classCount and namesCount.
When the count is set to 0, star imports are ignored. When the count is greater than zero, a star import is expanded if the number of resulting imports is less than the count.
Sound reasonable?

Allow empty line between groupings

Currently the impsort maven plugin squashes items together such as:

net.xyz.*
org.apache.*

This conflicts with other plugins such as formatter-maven-plugin that can be configured to break between those. There seems no such way to do with with impsort right now so it is constantly conflicting with formatting. Using above example, we need a fix to behave like this.

net.xyz.*

org.apache.*

Where line break is clear. It doesn't need to become the default but does need to be configurable. Currently impsort is capable of doing this as it does it with the separation between static imports and normal imports. However, the problem exists in both.

Using 'mybatis-3' as an example project and simply running impsort directly against it results in over 400 file changes due to simply deleting the present separation. So really this can be tested against any project but that one makes it more clear there is an issue.

To be clear, we are only talking the outermost left word. So in my example 'net' and 'org'. The others do not matter from what I've seen on formatting.

impsort-maven-plugin reports unparseable java file when using certain new java features

When using the patterns matching capability for instanceof as per https://docs.oracle.com/en/java/javase/17/language/pattern-matching-instanceof-operator.html the latest 1.8.0 plugin fails to parse the file containing this syntax.

I am using java 17.

As an example, the below fails ...

if (exception instanceof HttpStatusCodeException httpStatusCodeException) {
do stuff
}

Using the older approach works ..

if (exception instanceof HttpStatusCodeException) {
HttpStatusCodeException httpStatusCodeException = (HttpStatusCodeException) exception;
do stuff
}

mixing static imports of inner classes into other static imports (within same group)

We noticed that the impsort-maven-plugin sorts static imports differently to eclipse (or IntellijIdea with eclipseFormatter plugin) in certain cases.

While Eclipse and Intellij keep static imports per Type together, the plugin mixes static imports from a top-level class with those of an inner class.

Example:
Top-level class: A with constants BAR and FOO
Inner class A.C with constants EPSILON and OMEGA

public static class A {
  public static final String BAR = "bar";
  public static final String FOO = "foo";

  public static class C {
    public static final String EPSILON = "epsilon";
    public static final String OMEGA = "omega";
  }
}

Sorted static imports per eclipse:

import static com.foo.bar.A.BAR;
import static com.foo.bar.A.FOO;
import static com.foo.bar.A.C.EPSILON;
import static com.foo.bar.A.C.OMEGA;

Sorted static imports per plugin:

import static com.foo.bar.A.BAR;
import static com.foo.bar.A.C.EPSILON;
import static com.foo.bar.A.C.OMEGA;
import static com.foo.bar.A.FOO;

Is there any workaround we missed?
Best regards
Dane

Support * imports

I'm wondering if it's even possible to support expanding and/or collapsing * imports.

Our team utilises the Eclipse setting to expand all wildcard imports under a certain threshold (99) and collapse imports into the wildcard at 99 imports or above. Would that be something that could be supported within this plugin?

eclipse-import-preferences

Allow static imports mixed with non-static

At work we have the following eclipse import rules:

#Organize Import Order
#Fri Mar 16 10:43:04 CET 2012
17=\#
16=
15=\#javax
14=javax
13=\#java
12=java
11=\#groovy
10=groovy
9=\#org
8=org
7=\#net
6=net
5=\#junit
4=junit
3=\#com
2=com
1=\#com.corp
0=com.corp

There doesn't seem to have a way to configure the impsort-maven-plugin to have static group between 2 non-static.

WDYT about the best way to handle that ?

Remove empty line between imports

Hello There,

I'm using Eclipse IDE and i was wondering if there's a way to remove empty line between imports. If i don't use groups, i can still see 1 empty line between static and non-static imports. If I use groups, then i can see 1 empty line between each import groups.

Thanks,
Harry

Change cache to use relative path of the project rather than full path of system

Describe the bug

The cache works fine but it is listing the full build path. If not storing the cache in git, this is fine. However, when storing it in git, the full path is a problem. This is different than how this is implemented with formatter-maven-plugin. There is no expectation that every build machine have project in exact same place making sharing a non starter.

Versions (OS, Maven, Java, and others, as appropriate):

Confirmed with windows only at the moment but expecting the same on linux.

To Reproduce

Steps to reproduce the behavior:

  1. Run a build with impsort, check the impsort-maven-cache.properties in target folder
  2. See that it lists the entire path (far more than necessary)

looks like C:\xxxx\xxxx\xxxx\xxxx\myProject\src\main\java\somefile.java=XXXX

Expected behavior

Expected behaviour is to list the location relative to the pom that ran impsort so this can effectively be applied in git and shared.

Should be content only inside the build folder, using example would only be

\src\main\java\somefile.java

This will further help speed up processing as less is being written.

Our use case

We have formatting entirely automated so its on both windows and linux platforms. On linux, we are running in docker nodes through jenkins. The path changes depending on docker node used. We also do not enforce every developer use the same space on their machines. That would be extremely hard to enforce. We have the formatter plugin doing this now with it auto committing back to the repo without issue via jenkins process running the build so we end up with both windows and linux in the files (develoepr in windows commits on their own as no git hook yet). We would like to do the same here with impsort but cannot due to this current behaviour. Once this specific issue is addressed, we also need to remove the timestamp from the file and sort it like was done in formatter-maven-plugin 2.18.0. That is because some tools like maven plugins will actually keep writing the cache on windows as the hash table enforces no order. Only mentioning that here for now as this primary issue makes it not possible to go any further.

I'd be happy to work on this given I did the one over in the formatter plugin and with 2.18.0 release its working perfectly for caching.

Keeping third party imports in one group and java. and javax. imports in another

I am trying keep imports in following order:

static (alphabetically)
<blank-line>
com.<project>.*
<blank-line>
com,org (third party alphabetically)
<blank-line>
java
<blank-line>
javax
<blank-line>

I tried using following configuration:

    <configuration>
        <groups>com.projectName.,java.,javax.</groups>
        <staticGroups>java,*</staticGroups>
    </configuration>

is there a way to have third party library group between com.projectName and java.?

Additional blank lines above or below imports not allowed

For [reasons] I currently have a format (validated via formatter-maven-plugin) that has two blank lines above and two below the imports, which this plug-in has an issue with.
Since I simplified the whole imports ordering (why make it complicated when no one outside of diffs looks at them anyway) I'm considering to reduce it to one blank line each. But either way, the following issue might still be worth a little fix:

Currently, this plug-in seems to expect and enforce exactly one blank line above and one below the imports.
If possible, the sort goal should just preserve the number of blank lines around the imports.
But more importantly, the check goal should ignore the blank lines around the imports. Currently it complains with Imports are not sorted in [path] when there is more than one blank line around the imports, which is quite confusing and misleading. After comparing with how sort would like the imports, the only difference was the number of blank lines above and below.

I'm currently using this plug-in with its default configuration and executing the check goal during the validate phase.

Implement support for a cache file similar to formatter-maven-cache.properties for impsort

We waste a lot of time on impsort as it runs on all our files everytime even if files that hasn't really changed since last impsort.

on your other project: https://github.com/revelc/formatter-maven-plugin you have a cache that stores the hash of the file and then it does not attempt to format the file a second time if it has the same hash (and therefore unchanged)

By including the formatter-maven-cache.properties in our git repo and use the cachedir:
https://code.revelc.net/formatter-maven-plugin/format-mojo.html#cachedir
we save a lot of wasted time. ( 20s )

impsort:sort takes roughly the same amount of time as formatter:format (before cache file)

Could a similar cache with hashes be implemented for impsort:sort I would imagine that it would save us ~20s more.

(Bonus points if it would have the same format as formatter-maven-cache.properties as always run impsort:sort and formatter:format together, so we would probably use the same cache file for both)

externalizing funcionality

Is your feature request related to a problem? Please describe.
I want to use the import clean up functionality most of all as a library, not as a maven plugin.

Describe the solution you'd like
Separating the "real" code from the actual maven plugin

I know its quite annoying to have 2 projects to maintain, but i couldn't find any project that does the same job and working is working with recent code.

If you consider doing this, {{ImpSort}} should have a String as input, i had to work around this by creating temp files ...

Record with a record in it gives `the Java file contained parse errors`

Describe the bug

When running impsort-maven-plugin on a record with a record in it gives the Java file contained parse errors and 'record' cannot be used as an identifier as it is a keyword.

I have added a demo project where this issue can be reproduced, see bellow.

Versions (OS, Maven, Java, and others, as appropriate):

  • Affected version(s) of this project: 1.6.2
  • OS: macOS 12.3.1
  • Others:
    • Maven 3.8.5
    • Java 18.0.1

To Reproduce
Steps to reproduce the behavior (or a link to an example repository that reproduces the problem):

  1. Add the folloing file to a maven project where impsort-maven-plugin is configured
public record MyDTO(String myString, @JsonIgnore String name) {

    public PersonView getPerson() {
        return new PersonView(name);
    }

    record PersonView(String name) {
    }
}
  1. Run mvn package

Expected behavior
No error messages

Additional context
I get the following error message:

$ mvn process-sources   
impsort-maven-plugin:1.6.2:sort (sort-imports) @ demo ---
(line 19,col 5) 'record' cannot be used as an identifier as it is a keyword.
[INFO] Processed 524 files in 00:00.653 (Already Sorted: 524, Needed Sorting: 0)
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  3.786 s
[INFO] Finished at: 2022-05-24T20:59:34+02:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal net.revelc.code:impsort-maven-plugin:1.6.2:sort (sort-imports) on project demo: Error reading file MyDTO.java: file: MyDTO.java; reason: the Java file contained parse errors -> [Help 1]
[ERROR] 
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR] 
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException

I have attached a demo project where this issue can be reprodused, please see demo.zip.

When I don't have <exclude>**/MyDTO.java</exclude> running mvn process-sources failed with the error message above.

When having <exclude>**/MyDTO.java</exclude> running mvn package works fine, so the syntax in MyDTO.java seems to be ok

.

M2E configurator

Is your feature request related to a problem? Please describe.

It would be great if Eclipse could automatically detect the presence of this plugin when importing a Maven project that uses it. It would then import the plugin settings to configure the desired import order in the Eclipse project. This would mean that when I use the "organize imports" functionality in Eclipse, it would follow the import order configured in the Maven plugin.

Describe the solution you'd like

We could have a M2E connector similar to https://github.com/revelc/formatter-m2e-configurator. Or perhaps that existing code base could serve as M2E configurator for both Maven plugins?

Describe alternatives you've considered

I am not aware of any other mechanism for auto-discovery of such settings.

"Parse error" on java 16 record

Describe the bug
We get the following error when we have a java 16 record like

public record MyDTO(String name) {
}

we get the folloing stacktrace:

(line 3,col 1) Parse error. Found  "record" <IDENTIFIER>, expected one of  ";" "@" "class" "enum" "interface" "module" "open"
Problem stacktrace : 
  com.github.javaparser.GeneratedJavaParser.generateParseException(GeneratedJavaParser.java:12827)
  com.github.javaparser.GeneratedJavaParser.jj_consume_token(GeneratedJavaParser.java:12673)
  com.github.javaparser.GeneratedJavaParser.CompilationUnit(GeneratedJavaParser.java:170)
  com.github.javaparser.JavaParser.parse(JavaParser.java:123)
  com.github.javaparser.JavaParser.parse(JavaParser.java:306)
  net.revelc.code.impsort.ImpSort.parseFile(ImpSort.java:128)
  net.revelc.code.impsort.maven.plugin.AbstractImpSortMojo.lambda$execute$3(AbstractImpSortMojo.java:282)
  java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197)
  java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197)
  java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:183)
  java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197)
  java.base/java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948)
  java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
  java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
  java.base/java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150)
  java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173)
  java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
  java.base/java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:596)
  java.base/java.util.stream.ReferencePipeline$7$1.accept(ReferencePipeline.java:276)
  java.base/java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948)
  java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
  java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
  java.base/java.util.stream.ReduceOps$ReduceTask.doLeaf(ReduceOps.java:952)
  java.base/java.util.stream.ReduceOps$ReduceTask.doLeaf(ReduceOps.java:926)
  java.base/java.util.stream.AbstractTask.compute(AbstractTask.java:327)
  java.base/java.util.concurrent.CountedCompleter.exec(CountedCompleter.java:746)
  java.base/java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:295)
  java.base/java.util.concurrent.ForkJoinPool$WorkQueue.topLevelExec(ForkJoinPool.java:1016)
  java.base/java.util.concurrent.ForkJoinPool.scan(ForkJoinPool.java:1665)
  java.base/java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1598)
  java.base/java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:183)

Versions (OS, Maven, Java, and others, as appropriate):

  • impsort-maven-plugin 1.6.0

To Reproduce
Steps to reproduce the behavior (or a link to an example repository that reproduces the problem):

  1. Create a record like shown above
  2. add the plugin to pom.xml like shown on https://code.revelc.net/impsort-maven-plugin/
  3. Run mvn process-sources

Expected behavior
No errors on records.

Irrelevant 'throws' javadoc - Eclipse vs Impsort

I'm not sure this change of behavior is expected.

Given the class:

package bug;

import java.text.ParseException;

public class TextWithThrowJavadoc {

	/**
	 * @throws ParseException
	 */
	public String getSecuritypair() {
		return "text";
	}
}

Eclipse will keep the import ParseException as the exception is referred by the throws clause in javadoc. Impsort remove the import since 1.3.1

Is it an expected behavior ? I guess not as I might not want to express a RuntimeException in throws (as some static analysis tools would recommend not to do it), but I would want to keep them in the javadoc.

Error with Jdk 21 Pattern Matching for switch

Describe the bug

I am getting an issue with the impsort plugin when running the sort goal with JDK 21. The plugin appears to be incompatible with the new feature, pattern matching for switch I am receiving a parsing error during execution.
My implementation is the following

    private String getMessage(Object obj) {
        return switch (obj) {
            case Integer i -> String.format("int type %d", i);
            case Long l -> String.format("long type %d", l);
            case Double d -> String.format("double type %f", d);
            case String s -> String.format("String type %s", s);
            default -> obj.toString();
        };
    }

Versions (OS, Maven, Java, and others, as appropriate):

  • JAVA 21
  • Maven 3.9.6
  • impsort 1.9.0

To Reproduce

  1. implement Pattern Matching for switch in your code like my example above
  2. run mvn impsort:check

Exception
The exception
(line 52,col 18) Parse error. Found "i" <IDENTIFIER>, expected one of "!=" "%" "&" "&&" "(" "*" "+" "," "-" "->" "/" ":" "<" "<=" "==" ">" ">=" "?" "^" "instanceof" "|" "||" Problem stacktrace : com.github.javaparser.GeneratedJavaParser.generateParseException(GeneratedJavaParser.java:13933) com.github.javaparser.GeneratedJavaParser.jj_consume_token(GeneratedJavaParser.java:13778) com.github.javaparser.GeneratedJavaParser.SwitchEntry(GeneratedJavaParser.java:6369) com.github.javaparser.GeneratedJavaParser.SwitchExpression(GeneratedJavaParser.java:6216) com.github.javaparser.GeneratedJavaParser.UnaryExpressionNotPlusMinus(GeneratedJavaParser.java:4494) com.github.javaparser.GeneratedJavaParser.UnaryExpression(GeneratedJavaParser.java:4363) com.github.javaparser.GeneratedJavaParser.MultiplicativeExpression(GeneratedJavaParser.java:4226) com.github.javaparser.GeneratedJavaParser.AdditiveExpression(GeneratedJavaParser.java:4178) com.github.javaparser.GeneratedJavaParser.ShiftExpression(GeneratedJavaParser.java:4133) com.github.javaparser.GeneratedJavaParser.RelationalExpression(GeneratedJavaParser.java:4073) com.github.javaparser.GeneratedJavaParser.InstanceOfExpression(GeneratedJavaParser.java:3992) com.github.javaparser.GeneratedJavaParser.EqualityExpression(GeneratedJavaParser.java:3922) com.github.javaparser.GeneratedJavaParser.AndExpression(GeneratedJavaParser.java:3877) com.github.javaparser.GeneratedJavaParser.ExclusiveOrExpression(GeneratedJavaParser.java:3837) com.github.javaparser.GeneratedJavaParser.InclusiveOrExpression(GeneratedJavaParser.java:3797) com.github.javaparser.GeneratedJavaParser.ConditionalAndExpression(GeneratedJavaParser.java:3757) com.github.javaparser.GeneratedJavaParser.ConditionalOrExpression(GeneratedJavaParser.java:3712) com.github.javaparser.GeneratedJavaParser.ConditionalExpression(GeneratedJavaParser.java:3680) com.github.javaparser.GeneratedJavaParser.Expression(GeneratedJavaParser.java:3493) com.github.javaparser.GeneratedJavaParser.ReturnStatement(GeneratedJavaParser.java:7024) com.github.javaparser.GeneratedJavaParser.Statement(GeneratedJavaParser.java:5645) com.github.javaparser.GeneratedJavaParser.BlockStatement(GeneratedJavaParser.java:5865) com.github.javaparser.GeneratedJavaParser.Statements(GeneratedJavaParser.java:2773) com.github.javaparser.GeneratedJavaParser.Block(GeneratedJavaParser.java:5744) com.github.javaparser.GeneratedJavaParser.MethodDeclaration(GeneratedJavaParser.java:2170) com.github.javaparser.GeneratedJavaParser.ClassOrInterfaceBodyDeclaration(GeneratedJavaParser.java:1771) com.github.javaparser.GeneratedJavaParser.ClassOrInterfaceBody(GeneratedJavaParser.java:1275) com.github.javaparser.GeneratedJavaParser.ClassOrInterfaceDeclaration(GeneratedJavaParser.java:538) com.github.javaparser.GeneratedJavaParser.CompilationUnit(GeneratedJavaParser.java:156) com.github.javaparser.JavaParser.parse(JavaParser.java:125) com.github.javaparser.JavaParser.parse(JavaParser.java:305) net.revelc.code.impsort.ImpSort.parseFile(ImpSort.java:129) net.revelc.code.impsort.maven.plugin.AbstractImpSortMojo.lambda$execute$3(AbstractImpSortMojo.java:287) java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197) java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197) java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:184) java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197) java.base/java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:1024) java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:509) java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:499) java.base/java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151) java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174) java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) java.base/java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:596) java.base/java.util.stream.ReferencePipeline$7$1.accept(ReferencePipeline.java:276) java.base/java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:1024) java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:509) java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:499) java.base/java.util.stream.ReduceOps$ReduceTask.doLeaf(ReduceOps.java:960) java.base/java.util.stream.ReduceOps$ReduceTask.doLeaf(ReduceOps.java:934) java.base/java.util.stream.AbstractTask.compute(AbstractTask.java:327) java.base/java.util.concurrent.CountedCompleter.exec(CountedCompleter.java:754) java.base/java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:387) java.base/java.util.concurrent.ForkJoinTask.invoke(ForkJoinTask.java:667) java.base/java.util.stream.ReduceOps$ReduceOp.evaluateParallel(ReduceOps.java:927) java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:233) java.base/java.util.stream.ReferencePipeline.reduce(ReferencePipeline.java:662) net.revelc.code.impsort.maven.plugin.AbstractImpSortMojo.execute(AbstractImpSortMojo.java:316) org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:126) org.apache.maven.lifecycle.internal.MojoExecutor.doExecute2(MojoExecutor.java:328) org.apache.maven.lifecycle.internal.MojoExecutor.doExecute(MojoExecutor.java:316) org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:212) org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:174) org.apache.maven.lifecycle.internal.MojoExecutor.access$000(MojoExecutor.java:75) org.apache.maven.lifecycle.internal.MojoExecutor$1.run(MojoExecutor.java:162) org.apache.maven.plugin.DefaultMojosExecutionStrategy.execute(DefaultMojosExecutionStrategy.java:39) org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:159) org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:105) org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:73) org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:53) org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:118) org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:261) org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:173) org.apache.maven.DefaultMaven.execute(DefaultMaven.java:101) org.apache.maven.cli.MavenCli.execute(MavenCli.java:906) org.apache.maven.cli.MavenCli.doMain(MavenCli.java:283) org.apache.maven.cli.MavenCli.main(MavenCli.java:206) java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:103) java.base/java.lang.reflect.Method.invoke(Method.java:580) org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:283) org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:226) org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:407) org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:348) (line 52,col 62) Parse error. Found "case", expected "}" Problem stacktrace : com.github.javaparser.GeneratedJavaParser.generateParseException(GeneratedJavaParser.java:13933) com.github.javaparser.GeneratedJavaParser.jj_consume_token(GeneratedJavaParser.java:13778) com.github.javaparser.GeneratedJavaParser.Block(GeneratedJavaParser.java:5745) com.github.javaparser.GeneratedJavaParser.MethodDeclaration(GeneratedJavaParser.java:2170) com.github.javaparser.GeneratedJavaParser.ClassOrInterfaceBodyDeclaration(GeneratedJavaParser.java:1771) com.github.javaparser.GeneratedJavaParser.ClassOrInterfaceBody(GeneratedJavaParser.java:1275) com.github.javaparser.GeneratedJavaParser.ClassOrInterfaceDeclaration(GeneratedJavaParser.java:538) com.github.javaparser.GeneratedJavaParser.CompilationUnit(GeneratedJavaParser.java:156) com.github.javaparser.JavaParser.parse(JavaParser.java:125) com.github.javaparser.JavaParser.parse(JavaParser.java:305) net.revelc.code.impsort.ImpSort.parseFile(ImpSort.java:129) net.revelc.code.impsort.maven.plugin.AbstractImpSortMojo.lambda$execute$3(AbstractImpSortMojo.java:287)

Character encoding issues

I have a really strange bit of code I wrote a long time ago to test something. I happened to cause a bug with this formatter where it fails to process the file.

Code to cause the error

    public static void main(final String[] args) throws CharacterCodingException {
        final CharsetDecoder decoder = Charsets.ISO_8859_1.newDecoder();
        final CharsetEncoder encoder = Charsets.UTF_8.newEncoder();

        // Convert the byte array from starting inputEncoding into UCS2
        final byte[] bufferToConvert = "Hello World! £€".getBytes(Charsets.UTF_8);
        final CharBuffer cbuf = decoder.decode(ByteBuffer.wrap(bufferToConvert));

        // Convert the internal UCS2 representation into outputEncoding
        final ByteBuffer bbuf = encoder.encode(CharBuffer.wrap(cbuf));
        System.out.println(new String(bbuf.array(), 0, bbuf.limit(), Charsets.UTF_8));
    }

Here is the stack trace.

   at net.revelc.code.impsort.maven.plugin.AbstractImpSortMojo.fail (AbstractImpSortMojo.java:231)
    at net.revelc.code.impsort.maven.plugin.AbstractImpSortMojo.lambda$execute$3 (AbstractImpSortMojo.java:175)
    at java.util.stream.ReferencePipeline$3$1.accept (ReferencePipeline.java:193)
    at java.util.stream.ReferencePipeline$3$1.accept (ReferencePipeline.java:193)
    at java.util.stream.ForEachOps$ForEachOp$OfRef.accept (ForEachOps.java:184)
    at java.util.stream.ReferencePipeline$3$1.accept (ReferencePipeline.java:193)
    at java.util.Spliterators$ArraySpliterator.forEachRemaining (Spliterators.java:948)
    at java.util.stream.AbstractPipeline.copyInto (AbstractPipeline.java:481)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto (AbstractPipeline.java:471)
    at java.util.stream.ForEachOps$ForEachOp.evaluateSequential (ForEachOps.java:151)
    at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential (ForEachOps.java:174)
    at java.util.stream.AbstractPipeline.evaluate (AbstractPipeline.java:234)
    at java.util.stream.ReferencePipeline.forEach (ReferencePipeline.java:418)
    at java.util.stream.ReferencePipeline$7$1.accept (ReferencePipeline.java:270)
    at java.util.Spliterators$ArraySpliterator.forEachRemaining (Spliterators.java:948)
    at java.util.stream.AbstractPipeline.copyInto (AbstractPipeline.java:481)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto (AbstractPipeline.java:471)
    at java.util.stream.ReduceOps$ReduceTask.doLeaf (ReduceOps.java:747)
    at java.util.stream.ReduceOps$ReduceTask.doLeaf (ReduceOps.java:721)
    at java.util.stream.AbstractTask.compute (AbstractTask.java:316)
    at java.util.concurrent.CountedCompleter.exec (CountedCompleter.java:731)
    at java.util.concurrent.ForkJoinTask.doExec (ForkJoinTask.java:289)
    at java.util.concurrent.ForkJoinPool$WorkQueue.runTask (ForkJoinPool.java:1056)
    at java.util.concurrent.ForkJoinPool.runWorker (ForkJoinPool.java:1692)
    at java.util.concurrent.ForkJoinWorkerThread.run (ForkJoinWorkerThread.java:157)
Caused by: java.nio.charset.MalformedInputException: Input length = 1
    at java.nio.charset.CoderResult.throwException (CoderResult.java:281)
    at sun.nio.cs.StreamDecoder.implRead (StreamDecoder.java:339)
    at sun.nio.cs.StreamDecoder.read (StreamDecoder.java:178)
    at java.io.InputStreamReader.read (InputStreamReader.java:184)
    at java.io.BufferedReader.fill (BufferedReader.java:161)
    at java.io.BufferedReader.readLine (BufferedReader.java:324)
    at java.io.BufferedReader.readLine (BufferedReader.java:389)
    at java.nio.file.Files.readAllLines (Files.java:3205)
    at java.nio.file.Files.readAllLines (Files.java:3242)
    at net.revelc.code.impsort.ImpSort.parseFile (ImpSort.java:50)
    at net.revelc.code.impsort.maven.plugin.AbstractImpSortMojo.lambda$execute$3 (AbstractImpSortMojo.java:166)
    at java.util.stream.ReferencePipeline$3$1.accept (ReferencePipeline.java:193)
    at java.util.stream.ReferencePipeline$3$1.accept (ReferencePipeline.java:193)
    at java.util.stream.ForEachOps$ForEachOp$OfRef.accept (ForEachOps.java:184)
    at java.util.stream.ReferencePipeline$3$1.accept (ReferencePipeline.java:193)
    at java.util.Spliterators$ArraySpliterator.forEachRemaining (Spliterators.java:948)
    at java.util.stream.AbstractPipeline.copyInto (AbstractPipeline.java:481)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto (AbstractPipeline.java:471)
    at java.util.stream.ForEachOps$ForEachOp.evaluateSequential (ForEachOps.java:151)
    at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential (ForEachOps.java:174)
    at java.util.stream.AbstractPipeline.evaluate (AbstractPipeline.java:234)
    at java.util.stream.ReferencePipeline.forEach (ReferencePipeline.java:418)
    at java.util.stream.ReferencePipeline$7$1.accept (ReferencePipeline.java:270)
    at java.util.Spliterators$ArraySpliterator.forEachRemaining (Spliterators.java:948)
    at java.util.stream.AbstractPipeline.copyInto (AbstractPipeline.java:481)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto (AbstractPipeline.java:471)
    at java.util.stream.ReduceOps$ReduceTask.doLeaf (ReduceOps.java:747)
    at java.util.stream.ReduceOps$ReduceTask.doLeaf (ReduceOps.java:721)
    at java.util.stream.AbstractTask.compute (AbstractTask.java:316)
    at java.util.concurrent.CountedCompleter.exec (CountedCompleter.java:731)
    at java.util.concurrent.ForkJoinTask.doExec (ForkJoinTask.java:289)
    at java.util.concurrent.ForkJoinPool$WorkQueue.runTask (ForkJoinPool.java:1056)
    at java.util.concurrent.ForkJoinPool.runWorker (ForkJoinPool.java:1692)
    at java.util.concurrent.ForkJoinWorkerThread.run (ForkJoinWorkerThread.java:157)

"Use of patterns with instanceof is not supported"

Describe the bug

When running the sort goal on a Java 17 source file which uses instanceof patterns (e.g. if (obj instanceof Class<?> cl) { ... do something with cl ... }, we get an error:

(line 27,col 20) Use of patterns with instanceof is not supported.
(line 28,col 20) Use of patterns with instanceof is not supported.
(line 34,col 20) Use of patterns with instanceof is not supported.
(line 35,col 20) Use of patterns with instanceof is not supported.
(line 66,col 13) Use of patterns with instanceof is not supported.
(line 68,col 20) Use of patterns with instanceof is not supported.
(line 70,col 20) Use of patterns with instanceof is not supported.
(line 96,col 13) Use of patterns with instanceof is not supported.
(line 170,col 13) Use of patterns with instanceof is not supported.
(line 173,col 20) Use of patterns with instanceof is not supported.
(line 163,col 17) Use of patterns with instanceof is not supported.
(line 172,col 21) Use of patterns with instanceof is not supported.
(line 35,col 16) Use of patterns with instanceof is not supported.
(line 37,col 13) Use of patterns with instanceof is not supported.

Versions (OS, Maven, Java, and others, as appropriate):

  • Affected version(s) of this project: 1.9.0
  • OS: any
  • Others: JDK 17+

To Reproduce
Configure the plugin on a project using this syntax.

Additional context
The bug is likely due to misconfiguring javaparser. It should be configured to use the same JDK version that is used to compile the project (from the complier plugin), but is likely instead being configured to use the static instance or otherwise is not being configured with the correct source version.

See https://stackoverflow.com/questions/77117816/javaparser-lib-issue-parseproblemexception-use-of-patterns-with-instanceof-is for more context.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.