adding other modules in classpath for a Gradle plugin task - gradle

I have a Gradle plugin that works well so far, however, I am facing an issue in a multi-module project.
The plugin runs its task in every module of the project, but sometimes, I need to access classes from other modules to analyze them - typically, in the context of hexagonal architecture, I want to perform some checks on classes in infrastructure that implement an interface defined in domain module.
So, when the task runs (after the tests) within infrastructure module, it finds the class. But it's not able to load the interface (from domain) that the class implements. When I do :
Object interfaceLoadedDynamically = Class.forName(i.getName());
I clearly see it can't be loaded, and that prevents me from performing the checks I need to do.
here are :
the plugin
the task
Is there a way to configure one of them to say : "when you run within a module, make sure all the other project modules that have been compiled before are available in the classpath" ?
I've seen maybe I could use Gradle's Configuration , but I am really not sure where/how to start.

Related

Spring Boot Multi Module and Fat jar with Shared Features

Experts,
I need some expert advice on how to approach the below use case in spring boot.
I need to have a maven multi-module approach to my project.
I need to have a single jar as output of the final build process.
There are to be common modules for controllers, data access and other functionality
Other modules are to be created based on functionality domain for eg a module for Payroll, a module for Admin etc etc.
Each domain functional module will then have their own controllers extending the common controller, exception handler and so on.
Each module will also have its own set of thyme leaf pages.
The reason for following such an approach is we have development in phases and we will be rolling out based on functional modules.
Here are the issues that I can sense using this approach.
Where do I add the spring web dependency? If I add to the parent pom - it gets replicated across the children and there will be port conflict issues as each module loads. the same issue will also be there the moment I add it to two child modules.
How do I build the fat jar which has all the jars from all modules and works as the final deployment?
All the text that I read i can't see anything even close to what I am trying to achieve.
AD1. They will not unless you are trying to setup independent application context in each module. Of course you can do that(it might be complicated but I believe it's achievable), but for me it's an overkill. Personally I think it's better to have one application context and rely on scanning components that are present in classpath.
AD2. The structure in maven might be a little bit complicated and overwhelming at first glance but it makes sense. Here's how I see it:
Create a parent module that will aggregate each module in project and will declare library/plugin dependencies for submodules.
Create 1-N shared submodules that will be used in other modules. With come common logic, utils, etc.
Create 1-N submodules that will be handling your business logic
Create an application submodule that creates application context and loads configuration and components from classpath
Create a submodule that will be responsible for packaging process, either to war, jar, uber-jar or whatever else you desire. Maven jar plugin should do that for you. For executable uber-jar, you have dedicated tool from spring.
Now you can choose three ways(these ways I know) of loading your modules.
1. Include some modules in maven build based on the build configuration via maven profiles and let spring IoC container load all the components he finds in the classpath
2. Include all of the modules in maven build and load them depending on spring active profiles - you can think about it as of feature flag. You annotate your components or configuration class with #Profile("XYZ") telling spring IoC container whether to instantiate component or not. You will need (most flexible solution) to provide a property file which tells spring which profiles are active and thus which modules should be loaded
3. Mix of these two above.
Solution 1 pros:
build is faster (modules that are not included will be skipped during build)
final build file is light (modules that are not included are... not included ;))
nobody can run module that is not present
Solution 1 contras:
project descriptor in maven may explode as you might have many different profiles
Solution 2 pros:
it's fairly easy and fun to maintain modules from code
less mess in project descriptor
Solution 2 contras:
somebody can run module that is not intended to be run as it's present in classpath, but just excluded during runtime via spring active profiles
final build file might be overweight - unused code is still present in code
build might take longer - unused code will be compiled
Summary:
It's not easy to build well structured project from scratch. It's much more easier to create a monolith and then split it into modules. It's because if you already created a project, you've probably already identified all the domains and relations between them.
Over past 8 years of using maven, I honestly and strongly recommend using gradle as it's far more flexible than maven. Maven is really great tool, but when it comes to weird customization it often fails as it's build capabilities rely on plugins. You can't write a piece of code on the fly to perform some custom build behaviour while buidling your project, you must have a dedicated plugin for doing that. If such plugin exists it's fine, if it's not you will probably end up writing your own and handling its shipment, so anyone in your company can easily perform project build.
I hope it helps. Have fun ;)

Alternative way to define bootRun task in Gradle doesn't work

I usually define tasks in Gradle (using Groovy) like tasks.withType(Type); e.g.: tasks.withType(JavaCompile), tasks.withType(Test), etc.
Now, I want to do the same with some provided Spring Boot tasks, namely: bootRun and bootStartScripts, but Gradle cannot find it.
I know it's silly and I could get away just by using bootRun and bootStartScripts, but I would like to understand why those cannot be configured/defined in such way.
I guess with define you mean configure, because withType can only be used to configure existing tasks. It takes a task type (a class) and a closure that can be used to configure all available tasks of that type. This needs to be considered, because a project may contain multiple tasks of the same type that should actually do completely different things. Whether to configure all those tasks or just a specific one is important!
To pass the task type to the method withType you need to know the name of the class implementing the task type. This name is not necessarily related to the name(s) of the actual task(s). For the tasks test and compileJava of the Gradle Java Plugin those classes are org.gradle.api.tasks.testing.Test and org.gradle.api.tasks.compile.JavaCompile. Since those classes are provided by Gradle, they are automatically imported and can be referenced via their simple names Test and JavaCompile. But the Spring Boot Plugin is a third-party plugin, so the classes need to be referenced by their full names.
The task bootStartScripts from your question is of type CreateStartScript, that is provided by Gradle. Therefore it can be configured like this:
tasks.withType(CreateStartScripts) {
// configure
}
The task bootRun is of type org.springframework.boot.gradle.tasks.run.BootRun, that is provided by the Spring Boot Plugin. So you need to specify the full name:
tasks.withType(org.springframework.boot.gradle.tasks.run.BootRun) {
// configure
}

Gradle kotlin how to call function defined in parent?

When working with gradle multimodule project, is it possible to define functions in parent project but use them in submodules build.gradle.kts?
Note i do not need untyped tasks registered and called with strings... I want actual typesafe code to be shared to submodules.
Ideally without creating a plugin or using buildSrc.
Whats the most to the point way to share a class from parents build.gradle.kts to all submodules?
NOTE : this is not the same as sharing closure trough ext... you loose type safety, what i ask for is Type safety on submodule side.
I'm thinking that there is no way. When a Kotlin build script gets compiled, it will end up as a class called Build_gradle in the default package (i.e. empty package) that extends CompiledKotlinBuildScript. Any class that is defined within a script becomes a public nested class in its corresponding Build_gradle. When the subproject build script gets compiled, it has no access to the classpath that contains the parent projects build script. This makes sense, as there would be multiple Build_gradle files in the same (default) package.
I'd go for buildSrc, to solve the problem, but I'm speculating that what you also wanted was some sort of nice separation of concerns in a multimodule project, not having unrelated projects knowing about what others need to communicate. What you could do to minimize the exposure is to only keep the API (interfaces, data classes) in buildSrc and have a script plugin in a parent project provide the implementation.

Gradle Plugin that must load the compiled classes from the project

As part of writing a Gradle plugin for Flyway, we stumbled upon a problem when dealing with Java migrations.
What is the best way to provide a Gradle plugin access on its classpath to the compiled classes of the project so that it can load and execute them?
So the situation is that we have a plugin that adds a task that wants to execute code contained in the project that the plugin is applied to. In this case, the task (class) should have an input property of type Iterable<File> that gets configured (by the plugin) with the class path of the code to be executed (e.g. sourceSets.main.runtimeClasspath). The task can then choose between the following ways to execute the code:
The task uses project.javaexec {} to execute the code in a separate JVM. If the code isn't directly executable, the task may need to inject some bootstrap code onto the javaexec class path. A potential alternative to using project.javaexec is to use a JavaExec task in the first place.
The task creates a new class loader, populates it with the class path, loads and instantiates the classes that serve as the entry point(s) to the API, and makes use of them as appropriate. If the task is written in Groovy, it can leverage duck typing, and no reflective code will be necessary beyond creating the entry points.

Maven Multi Module benefits over simple dependency

I have some years of experience with maven projects, even with multi modules ones (which has made me hate the multi modules feature of maven (so the disclaimer is now done)) and even if I really like maven there is something I cannot get a clear answer about :
What is a typical usecase of a multi module maven project ? What is the added value of such a structure compared to simple dependencies and parent pom ?
I have seen a lot of configuration of multi module projects but all of them could have clearly been addressed by creating a simple structure of dependency library living their own life as deliverables (even with a parent pom, as a separate deliverable : factorising depedencies and configuration) and I haven't found any usecase where I can clearly see an added value of the multi module structure.
I have always found that this kind of structure brings an overkilling complexity with no real benefit : where am I missing something ? (to be truly honest, I can get that some ear can benefit from this kind of structure but except from that particular usecase, any other real use and benefit ?)
Here's a real life case.
I have a multi-module project (and to your rant... I haven't seen any complications with it.) The end result is a webapp but I have different modules for api, impl, and webapp.
12 months after creating the project I find that I have to integrate with Amazon S3 using a stand-alone process run from a jar. I add a new module which depends on api/impl and write my code for the integration in the new module. I use the assembly plugin (or something like it) to create a runnable jar and now I have a war I can deploy in tomcat and a process I can deploy on another server. I have no web classes in my S3 integration process and I have no Amazon dependencies in my webapp but I can share all the stuff in api and impl.
3 months after that we decide to create a REST webapp. We want to do it as a separate app instead of just new URL mappings in the existing webapp. Simple. One more module, another webapp created as the result of the maven build with no special tinkering. Business logic is shared easily between webapp and rest-webapp and I can deploy them as needed.
The major benefit of multi modules are
one single maven command to build all your modules at once.
and the most important : maven take care of the build order for you.
configuring your CI-server is also very easy: one single jenkins job to build everything.
I already worked in a project with about 30 submodules. Sometimes, you need to change something in more than module, and running one single command and being sure that everything that need to be compiled is compiled in the correct order is a must.
EDIT
Why 30 submodules ?
Huge framework with lot's a features, lot's of developers, separation of features on a module base. It's a real life use case and the separation of the code into module was really meaningful.
I think you are correct in that most project that use multi modules, actually don't need them.
At where I work we use multimodule projects (and I think that for a good reason). We have something similar to a service oriented architecture, so each application
A client module
An interface module (which has shared objects between the client and implementation)
an implementation module
a war module
I agree that putting that implementation and war module in the same actual module would be ok, but the (arguably) benefit of this is that is very clear division between the classes that solve the problem and how the application communicates with the external world.
In previous projects that involved just a web application, I've tried to put everything in the same module, as it made testing easier, given the modules I was using.
Multi modules can help you with re-use your code.
It's one of the best benefits you'll feel in work.
Imagine if you have 3 web projects with a security layer, You'll have to copy paste your code 3 times and trying connect it with each project.
But what if you create a security module a project with a specific job.
It'll be easy to use it by injecting it to your app and then boom it works.
Also as mentioned in #ben75's answer the one maven build command and the correct order of building all your used jars. You'll think no more about which depends on another.
I find maven modules extremely useful for the following reasons:
Architecture layering and boundaries
For example, I make a maven module application-contract which contains the interfaces my presentation layer sees. So I have UI->Presenter-> application-contract <-application-impl <- infrastructure -> domain. This way, I know that my presentation/UI layer will not have access to classes from my Domain/application layers. If domain classes are not in classpath when I code in UI, I cant use them. And I like it this way (utilizing the class path restrictions). Perhaps Java 9 modules can solve this problem too, but (unfortunately) I have work with Java 8.
Running tests in one module each time
When I change code to a layer which is a module (as mentioned previously) I can run its tests only, without re-runing tests from code I did not change. This gives me speed. My presentation layer tests need ~3 seconds (for 300 tests). Every time I change code to a Presenter or whatever below application layer, I don't want my database H2 integration tests to run. Or My Image processing tests to run. Because these do IO and they are slow.
Building
Pretty much the same thing. When I change code to UI, i have only to build and deploy UI stuff (my UI is in Java).

Resources