Delombok a java file per feature - java

I want to delombok a java file. Per feature I mean that I want to delombok a val usage at first. It means to convert parts of code like val x = "some string"; to pure java code String x = "some string";. Also, the other Lombok features can be converted to plain java code. The Lombok project includes this functionality, you can find more details here.
In current project we decided to stop using it for various reasons. For example I am well to generate getters and setters using IDE. Also, as for me, val usage makes code less readable. I tried one time to delombok the project using IDE plugin, but it makes the code unreadable and awful. Probably there is a way where I can delombok by small steps - for a chosen file and for a chosen Lombok feature.
How can I do this in terminal or in IntelliJ IDEA?
Probably there is no out of the box solution, but you can point me direction where I should look at.

You can use the Lombok plugin in IntelliJ which does the delombok automatically IntelliJ > Refactor > Delombok.
The plugin can be found at :
https://plugins.jetbrains.com/plugin/6317-lombok
Also, project Lombok supports the command line operations, refer the guide :
https://projectlombok.org/features/delombok
I hope this helps. Cheers.

Related

How can a consistent Java code format be enforced?

I'm looking for a way to force developers to use the same Java code formatting rules. My requirements are:
Gradle integration
Task that checks if code is correctly formatted. This will be used on CI to cause a build failure if incorrectly formatted code is submitted
Task that fixes incorrectly formatted code (nice-to-have)
IntelliJ integration
Incorrectly formatted code can be fixed within the IDE via the "Reformat Code" action
Code that is generated by the IDE (e.g. getter/setter generation) conforms to the rules
Supports the OpenJDK/Oracle Java formatting rules
Currently I'm using Spotless with the following configuration
spotless {
java {
toggleOffOn()
eclipse().configFile("${project.rootDir}/tools/eclipse-java-formatter.xml")
indentWithSpaces()
removeUnusedImports()
}
}
For IntelliJ integration, I've installed the Eclipse Code Formatter plugin and configured it to use the same rules as Spotless.
This approach meets all of the requirements above except for 2.2 i.e. any code generated by IntelliJ must be reformatted before it conforms to the formatting rules. A further problem is that the imports seem to be arbitrarily reordered when code is reformatted. This generates a lot of spurious changes which makes pull requests more difficult to review.
Is there another approach (e.g. CheckStyle) that does not suffer from these shortcomings?
You could use the Google Java Format, which has plugins for the aforementioned IDEs (IntelliJ IDEA, Eclipse), it provides integrations with tools such as Maven, Gradle, or SBT, and provides means to run the formatter as pre-commit hook or when pushing the code to Github with Github actions.
In their README they also mention the imports issue and how to fix it for IntelliJ IDEA, and more insights are provided e.g.: on how to handle it on Spotless Gradle plugin, when using the Maven Spotless plugin, or for Github actions.
A drawback for your specific case may be that the tool enforces the Google Java style guide, which was praised and recommended by the Oracle Java team as described in the Oracle Java magazine. It also provides the option to use the AOSP code style.
Below a snippet for spotless Gradle configuration, considering imports ordering:
spotless {
java {
importOrder() // standard import order
importOrder('java', 'javax', 'com.acme', '') // or importOrderFile
// You probably want an empty string at the end - all of the
// imports you didn't specify explicitly will go there.
removeUnusedImports()
googleJavaFormat() // has its own section below
eclipse() // has its own section below
prettier() // has its own section below
clangFormat() // has its own section below
licenseHeader '/* (C) $YEAR */' // or licenseHeaderFile
}
}
Checkstyle supports most of your requirements.
Gradle Integration:
plugins {
id 'checkstyle'
}
checkstyle {
toolVersion = checkstyleVersion
config = rootProject.resources.text.fromFile(checkstyleRulesRootPath) # Loads configuration from a file
ignoreFailures = false # Causes build to fail
maxWarnings = 0 # Fails even for warnings
}
It do not fixes code automatically (AFAIK).
IntelliJ integration:
There's Checkstyle plugin which you can configure to display warnings as you're coding.
You can also configure IntelliJ autoformatting to use these rules.
Formatting rules
Here is the configuration for Oracle/Sun specifications in checkstyle.
I think you can use it p3c plugin
I use formatter-maven-plugin and import-maven-plugin
Those plugins have validate/check goals that I use in our CI tool to validate incoming PRs.
They also have gradle variants. Checkout here
I can help you here. Mainly, you have asked two main problems here:
Incorrectly formatted code can be fixed within the IDE via the "Reformat Code" action
For this, you need to write a code template. We use a specific code template in our organisation. Now, you need to import this XML code template under Settings > Code Style.
Now the code will by default be formatted the way the template has been written.
Or use Ctrl +Shift+ F as the eclipse shortcut(enabled in intelliJ).
Support for the OpenJDK/Oracle Java formatting rules can be taken care of within the same template. Please refer their code template as default one provided in Eclipse.
Code that is generated by the IDE (e.g. getter/setter generation) conforms to the rules
This link will help. Please explore more on how to write the custom code templates.
To restrict all the developers to not to push the wrong format of the code, you need to write a GIT hook. It will not allow the code to be pushed unless the code complies with basic rules provided in the custom script of the hook. Nobody needs to do anything on local intelliJ, the git hook will act from the remote GIT repo. Here is one supporting link.
I have provided crisp information here because it is more the matter of customized rules that will be there in your code templates.
Other questions:
Task that checks if code is correctly formatted. This will be used on CI to cause a build failure if incorrectly formatted code is submitted.
When you will restrict the committed code using git hooks, there shall never be any code unformatted on the repo. So, you don't need it as part of CI build.
It may be done by providing a pipeline script that will trigger a method having the git location of your code. It looks a tedious thing to me.
Hope, all your questions are answered.

Eclipse New Java Class Wizard in VS Code

Is there a way to create Java class in VS Code similar to Eclipse New Java Class Wizard?
I would like VS Code to add package and class declarations automatically like Eclipse does.
Couldn't find relevant info in the docs and relevant functionality in plugins.
I faced a similar issue, coming from Eclipse/IDEA background, you can find it difficult to not have a feature in your java IDE to create a new classes, packages etc.
You can use the below VSCode extension : https://github.com/jiangdequan/vscode-java-saber
It is a very handy extension.It provides support/wizard for:
New: Java files(annotation/class/interface/enum/package/JSP/HTML)
Generate Getters and Setters
Copy Qualified Name
Sort Project By Name
Run Maven Goals
Generate Docs
You can try this extension.Search for vscode-java-saber in the extension search and install it.

library for Java/Groovy code analysis

I have a project that should analyze Java and Groovy code and build a special script from the source code.
Googling code analysis libraries didn't really result in anything useful for me.
But someone gave me a link to the Spoon project to analyze Java code.
Right now, the only parts that I need from Spoon are to give a set of .java files and it will return me the source code in a big data structure provided by Spoon.
So far the code that I use:
private CtPackage analyzeSourceCode()
{
Launcher spoon = new Launcher();
this.javaFiles.forEach(spoon::addInputResource);
spoon.buildModel();
return spoon.getFactory().Package().getRootPackage();
}
After which, I build up whatever I need from the packages returned.
(Note that I also require the actual executions, not only the data structures and members of the source code.)
But this only works for .java files and not for .groovy files... which brings me back to the point where I need a library to analyze Groovy code.
This one also doesn't allow me to use Java and Groovy together, so I need something else anyway.
Can anyone tell me what I am doing wrong in my google searches or provide me with links to a library that can analyze Java and Groovy code?

Strip ScalaSignature annotation from resulting binaries

How can you strip java or scala annotations programmatically?
One of the deliverables for my current project is my code, plus whatever dependencies my code relies on, as an uber-jar. We're building an SDK therefore any of the included dependencies need to be renamed as to not interfere with the SDK client's dependencies (meaning if we're using apache commons version X, and they're using version Y, there aren't any conflicts). We used sbt-assembly to rename the packages our code relies on. For example org.apache.* -> com.mycompany.org.apache.*
Our project is largely written in scala and we're using sbt to build. Recently I determined that shading causes problems with the ScalaSignature annotation. This in turn causes build problems when the uber-jar is used in the client's project.
I have determined that removing ScalaSignature resolves the problem. I used ProGuard to do this, however that tool is overkill for what we are trying to achieve. I'm just curious if anyone out there has found a tool that can strip specified annotations. Or even better, a tool that will rename the packages while preserving ScalaSignature in a way that scalac is happy with.
You might want to check JavaAssist library, which clearly allows to get/add annotations dynamically.
Following that, it should be theoretically possible to use AnnotationsAttribute in the following way (haven't tried myself but let us know if the below has worked):
MethodInfo minfo = m.getMethodInfo();
AnnotationsAttribute attr = (AnnotationsAttribute)
minfo.getAttribute(AnnotationsAttribute.invisibleTag);
Annotation[] annotations = attr.getAnnotations();
// ...remove the unnecessary annotation from array...
attr.setAnnotations(annotations);

How parse xml file in groovy and put it in a pojo?

Someone told me that groovy xml parser is better and easy, my question how to use groovy inside java to parse an xml file and put it in a pojo object ?
thanks.
Groovy compiler has a feature called "joint-compilation". That is used for compiling groovy project with another java project. It is defined in their site as
Joint compilation means that the Groovy compilation will parse the Groovy source files, create stubs for all of them, invoke the Java compiler to compile the stubs along with Java sources, and then continue compilation in the normal Groovy compiler way. This allows mixing of Java and Groovy files without constraint.
But the catch is as your project's codebase increases, it causes some problems with static references. If you are compiling your code using Maven or use Ant scripts then life becomes easier.
Ref Link : http://groovy.codehaus.org/The+groovyc+Ant+Task
You could also look into this link http://today.java.net/pub/a/today/2004/08/12/groovyxml.html where the user has tried a lot of options including Groovy.

Categories