Use gradle plugin to configure another gradle plugin - gradle

I want to implement a gradle plugin which changes the project.version according to the configuration of the plugin and then use the changed project.version to configure another gradle plugin e.g. for building containers. The problem is now that both configurations are evaluated at the same time and therefore the changes to project.version are not applied at the time the second plugin is configured.
I search the Gradle documentation but found nothing regarding my problem.
build.gradle
class VersionPluginExtension {
String major
String minor
String patch
}
class VersionPlugin implements Plugin<Project> {
void apply(Project project) {
def extension = project.extensions.create('versionPlugin', VersionPluginExtension)
project.afterEvaluate {
project.version = "${extension.major}.${extension.minor}.${extension.patch}"
}
project.task('showVersion') {
doLast {
println "${project.version}"
}
}
}
}
class ContainerPluginExtension {
String version
}
class ContainerPlugin implements Plugin<Project> {
void apply(Project project) {
def extension = project.extensions.create('containerPlugin', ContainerPluginExtension)
project.task('build') {
doLast {
println "${extension.version}"
}
}
}
}
apply plugin: VersionPlugin
apply plugin: ContainerPlugin
versionPlugin {
major = '1'
minor = '1'
patch = '1'
}
containerPlugin {
version = project.version
}
I expect that the task build returns 1.1.1 and not unspecified but I think it's not possible in this way. I hope someone can point me in the right direction.
Thanks!

Move the definition of version from the containerPlugin block to the plugin definition :
class ContainerPlugin implements Plugin<Project> {
void apply(Project project) {
def extension = project.extensions.create('containerPlugin', ContainerPluginExtension)
project.afterEvaluate {
extension.version = project.version
}
project.task('build') {
doLast {
println "${extension.version}"
}
}
}
}
Result :
$ gradle build
> Task :build
1.1.1

The solution to the problem above looks like this:
class VersionPluginExtension {
String major
String minor
String patch
private String version
String getVersion() {
if (!version)
return "${major}.${minor}.${patch}"
return version
}
}
class VersionPlugin implements Plugin<Project> {
void apply(Project project) {
def extension = project.extensions.create('versionPlugin', VersionPluginExtension)
project.task('showVersion') {
doLast {
println "${extension.version}"
}
}
}
}
class ContainerPluginExtension {
String version
}
class ContainerPlugin implements Plugin<Project> {
void apply(Project project) {
def extension = project.extensions.create('containerPlugin', ContainerPluginExtension)
project.task('build') {
doLast {
println "${extension.version}"
}
}
}
}
apply plugin: VersionPlugin
apply plugin: ContainerPlugin
versionPlugin {
major = '1'
minor = '1'
patch = '1'
}
project.version = versionPlugin.version
containerPlugin {
version = project.version
}
Result:
> Configure project :
1.1.1
> Task :showVersion
1.1.1
> Task :build
1.1.1

Related

How to generate OpenAPI via Gradle for Amazon Selling Partner API models?

I'm new to Gradle (using 7.3.2) and currently trying to integrate org.openapi.generator's openApiGenerate task for all json OpenAPI template files of Amazon's selling partner API models from https://github.com/amzn/selling-partner-api-models.
plugins {
id 'org.ajoberstar.grgit' version '4.1.1'
id 'org.openapi.generator' version '5.3.0'
}
import org.ajoberstar.grgit.Grgit
project.ext.repoDirectory = "$buildDir/selling-partner-api-models"
project.ext.basePackage = "com.amazon.sellingpartner"
tasks.register('deleteRepo', Delete) {
delete project.ext.repoDirectory
}
class CloneSpapi extends DefaultTask {
#Input
String url = 'https://github.com/amzn/selling-partner-api-models.git'
#TaskAction
def clone() {
println 'Cloning Amazon Selling Partner OpenAPI from github ...'
def grgit = Grgit.clone(dir: project.ext.repoDirectory, uri: url)
grgit.close()
println 'done'
}
}
tasks.register('cloneSpapi', CloneSpapi) {
description 'Clones Amazon Selling Partner OpenAPI from github'
dependsOn tasks.named('deleteRepo')
}
interface GenerateParameters extends WorkParameters {
RegularFileProperty getJsonFile()
DirectoryProperty getOutputDir()
}
abstract class GenerateApi implements WorkAction<GenerateParameters> {
#Override
void execute() {
def file = parameters.jsonFile.get().getAsFile()
def modelName = file.getName().replace('.json', '')
println modelName + ": " + file
}
}
abstract class GenerateApis extends DefaultTask {
private final WorkerExecutor workerExecutor
#Input
abstract String directory = "$project.ext.repoDirectory/models"
#Inject
GenerateApis(WorkerExecutor workerExecutor) {
this.workerExecutor = workerExecutor
}
#TaskAction
void generateFiles() {
ConfigurableFileTree tree = project.fileTree(dir: directory)
tree.include '**/*.json'
Set<File> modelFiles = tree.getFiles().sort()
WorkQueue workQueue = workerExecutor.noIsolation()
modelFiles.each { File file ->
workQueue.submit(GenerateApi.class) { GenerateParameters parameters ->
parameters.jsonFile = file
}
}
}
}
tasks.register('generateApis', GenerateApis) {
}
openApiGenerate {
generatorName = "java"
inputSpec = // file
outputDir = "$buildDir/generated".toString()
invokerPackage = "$project.ext.basePackage"
apiPackage = "$project.ext.basePackage" + ".api.modelName" // modelName from
modelPackage = "$project.ext.basePackage" + ".model.modelName" // modelName here
configOptions = [
dateLibrary: "java8"
]
}
To simplify things, I have added a simple 'cloneSpapi' task to clone the repository.
gradle -q cloneSpapi
How do I call the openApiGenerate task for each template file?
I have now used the swagger.io library directly and was able to call the code generator directly.
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("io.swagger:swagger-codegen:2.4.24")
}
}
plugins {
id 'org.ajoberstar.grgit' version '4.1.1'
}
import io.swagger.codegen.DefaultGenerator
import io.swagger.codegen.config.CodegenConfigurator
import org.ajoberstar.grgit.Grgit
project.ext.repoDirectory = "$buildDir/selling-partner-api-models"
project.ext.basePackage = "com.amazon.sellingpartner"
project.ext.outputDir = new File(project.buildDir, '/generated')
tasks.register('deleteRepo', Delete) {
delete project.ext.repoDirectory
}
class CloneSpapi extends DefaultTask {
#Input
String url = 'https://github.com/amzn/selling-partner-api-models.git'
#TaskAction
def clone() {
println 'Cloning Amazon Selling Partner OpenAPI from github ...'
def grgit = Grgit.clone(dir: project.ext.repoDirectory, uri: url)
grgit.close()
println 'done'
}
}
tasks.register('cloneSpapi', CloneSpapi) {
description 'Clones Amazon Selling Partner OpenAPI from github'
dependsOn tasks.named('deleteRepo')
}
interface GenerateParameters extends WorkParameters {
RegularFileProperty getJsonFile()
DirectoryProperty getTemplateDir()
DirectoryProperty getOutputDir()
Property<String> getBasePackage()
}
abstract class GenerateApi implements WorkAction<GenerateParameters> {
#Override
void execute() {
def file = parameters.jsonFile.get().getAsFile()
def modelName = file.getName().replace('.json', '')
println "Generating OpenAPI for $modelName"
def basePackage = parameters.basePackage.get()
def config = new CodegenConfigurator()
config.setInputSpec(file.toString()) // The swagger API file
config.setLang("java")
config.setTemplateDir(parameters.templateDir.get().toString())
config.setOutputDir(parameters.outputDir.get().toString()) // The output directory, user-service-contract/build/user-service-server/
config.setInvokerPackage(basePackage)
config.setApiPackage(basePackage + ".api." + modelName) // Package to be used for the API interfaces
config.setModelPackage(basePackage + ".model." + modelName) // Package to be used for the API models
config.setAdditionalProperties([
'dateLibrary' : 'java8', // Date library to use
'useTags' : 'true' // Use tags for the naming
])
def generator = new DefaultGenerator();
generator.opts(config.toClientOptInput());
generator.generate()
}
}
abstract class GenerateApis extends DefaultTask {
private final WorkerExecutor workerExecutor
#Input
abstract String directory = "$project.ext.repoDirectory/models"
#Inject
GenerateApis(WorkerExecutor workerExecutor) {
this.workerExecutor = workerExecutor
}
#TaskAction
void generate() {
ConfigurableFileTree tree = project.fileTree(dir: directory)
tree.include '**/*.json'
Set<File> modelFiles = tree.getFiles().sort()
WorkQueue workQueue = workerExecutor.noIsolation()
modelFiles.each { File file ->
workQueue.submit(GenerateApi.class) { GenerateParameters parameters ->
parameters.jsonFile = file
parameters.templateDir = new File(project.ext.repoDirectory, 'clients/sellingpartner-api-aa-java/resources/swagger-codegen/templates')
parameters.outputDir = project.ext.outputDir
parameters.basePackage = project.ext.basePackage
}
}
}
}
tasks.register('deleteGenerated', Delete) {
delete project.ext.outputDir
}
tasks.register('generateApis', GenerateApis) {
dependsOn tasks.named('deleteGenerated'), tasks.named('cloneSpapi')
}

Execute the jar compiled by Gradle, cause "there is no main class"

The version of the gradle is 6.3-all. And here is my build.gradle:
plugins {
id 'java'
id 'org.jetbrains.kotlin.jvm' version '1.3.72'
}
group 'com.dennis'
version '1.0-SNAPSHOT'
repositories {
mavenLocal()
mavenCentral()
}
jar {
from {
configurations.runtime.collect { zipTree(it) }
}
manifest {
attributes 'Main-Class': 'com.dennis.tcp.robot.RobotClient'
}
}
dependencies {
/*...*/
}
compileKotlin {
kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
kotlinOptions.jvmTarget = "1.8"
}
tasks.withType(JavaCompile) {
options.encoding = "UTF-8"
}
And here is settings.gradle
rootProject.name = 'robot'
And here is the main class:
package com.dennis.tcp.robot;
/*import ignored*/
public class RobotClient {
private static final String URL = "192.168.10.140";
private static final int PORT = 9760;
public static void main(String[] args) {
NioEventLoopGroup group = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap();
try {
bootstrap.group(group)
.channel(NioSocketChannel.class)
.option(ChannelOption.SO_KEEPALIVE,true)
.handler(new RobotClientInitializer());
ChannelFuture future = bootstrap.connect(URL, PORT).sync();
future.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
group.shutdownGracefully();
}
}
}
The packaging progress went well but the output jar cannot be executed and give the Exception of no main class
The jar file shows the main class RobotClient is compiled indeed. However, the java -jar cannot execute or find the mainclass.
Why did this happend?

Run/Debug JUnit 5 Tests using Gradle and Mapstruct

I am trying to run and debug JUnit 5 Tests that use Mapstruct using both Visual Studio Code and Eclipse, but with no luck.
What works is to run the Test goal on Gradle. It runs the tests properly and show a result but when I try to run or debug the same test "manually" using the IDE, it throws an exception, always related to not being able to find the Mapper implementations or not being able to Autowire the clases, etc.
I have tried different things but with similar results, such as Autowire the Mapper, creating an instance of the Mapper in a method using #Before annotation... but always with no success.
Here is an example of a Mapper:
AddressMapper.java
package com.myorg.ccr.simulator.b2b.mapping;
import com.myorg.myproject.model.AddressDTO;
import com.myorg.myproject.model.StateDTO;
import com.myorg.xsd.b2b.upsertcustomer.Address;
import org.mapstruct.AfterMapping;
import org.mapstruct.BeanMapping;
import org.mapstruct.InheritInverseConfiguration;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.MappingTarget;
import org.mapstruct.ReportingPolicy;
import org.mapstruct.factory.Mappers;
#Mapper(unmappedTargetPolicy = ReportingPolicy.IGNORE,
unmappedSourcePolicy = ReportingPolicy.IGNORE,
uses = {DateMapper.class, UUIDMapper.class, StateMapper.class})
public interface AddressMapper {
AddressMapper INSTANCE = Mappers.getMapper(AddressMapper.class);
#BeanMapping(ignoreByDefault = true)
#Mapping(target = "externalAddressId", source = "externalAddressId")
#Mapping(target = "street1", source = "streetAddress")
#Mapping(target = "street2", source = "streetAddress2")
#Mapping(target = "postOfficeBox", source = "POBox")
#Mapping(target = "city", source = "city")
#Mapping(target = "postalCode", source = "postalCode")
#Mapping(target = "salutation", source = "recipientSalutation")
#Mapping(target = "phone", source = "recipientPhone")
#Mapping(target = "comments", source = "comments")
AddressDTO addressToAddressDTO(Address address);
#InheritInverseConfiguration
Address addressDTOToAddress(AddressDTO address);
#AfterMapping
default void setStatus(Address address, #MappingTarget AddressDTO addressDTO) {
StateDTO state = StateMapper.INSTANCE.addressToState(address);
addressDTO.setStatus(state);
}
#AfterMapping
default void setSourceCreatedUpdatedDate(Address address, #MappingTarget AddressDTO addressDTO) {
if (address != null) {
addressDTO.setSourceCreatedDate(DateMapper.asDate(address.getSourceCreatedDate()));
addressDTO.setSourceUpdatedDate(DateMapper.asDate(address.getSourceUpdatedDate()));
}
}
#AfterMapping
default void useTypeToAddressNumber(Address address, #MappingTarget AddressDTO addressDTO) {
if (address != null && address.getType() != null && !address.getType().isEmpty()) {
switch (address.getType()) {
case "Billing":
addressDTO.setAddressNumber(1);
break;
case "Delivery":
addressDTO.setAddressNumber(2);
break;
case "Packing Station":
addressDTO.setAddressNumber(3);
break;
case "Post Office":
addressDTO.setAddressNumber(4);
break;
default:
addressDTO.setAddressNumber(null);
}
}
}
#AfterMapping
default void addressNumberToType(AddressDTO addressDTO, #MappingTarget Address address) {
if (addressDTO != null && addressDTO.getAddressNumber() != null) {
switch (addressDTO.getAddressNumber()) {
case 1:
address.setPrimaryFlag("Y");
address.setType("Billing");
break;
case 2:
address.setPrimaryFlag("N");
address.setType("Delivery");
break;
case 3:
address.setPrimaryFlag("N");
address.setType("Packing Station");
break;
case 4:
address.setPrimaryFlag("N");
address.setType("Post Office");
break;
default:
address.setPrimaryFlag("N");
address.setType(null);
}
}
}
#AfterMapping
default void contactFullname(Address address, #MappingTarget AddressDTO addressDTO) {
String firstName = address.getRecipientFirstName();
String lastName = address.getRecipientLastName();
if (firstName != null && !firstName.isEmpty() && lastName != null && !lastName.isEmpty()) {
addressDTO.setContactFullname(firstName + " " + lastName);
} else if ((firstName == null || firstName.isEmpty()) && lastName != null && !lastName.isEmpty()) {
addressDTO.setContactFullname(lastName);
} else if (firstName != null && !firstName.isEmpty() && (lastName == null || lastName.isEmpty())) {
addressDTO.setContactFullname(firstName);
}
}
#AfterMapping
default void addressRecipientName(AddressDTO addressDTO, #MappingTarget Address address) {
if (addressDTO != null && addressDTO.getContactFullname() != null && !addressDTO.getContactFullname().isEmpty()) {
address.setRecipientFirstName(addressDTO.getContactFullname());
}
}
#AfterMapping
default void setActiveFlag(AddressDTO addressDTO, #MappingTarget Address address) {
String activeFlag = "N";
if (addressDTO != null) {
activeFlag = StateMapper.INSTANCE.stateToActiveFlag(addressDTO.getStatus());
}
address.setActiveFlag(activeFlag);
}
#AfterMapping
default void setDeletedFlag(AddressDTO addressDTO, #MappingTarget Address address) {
String deletedFlag = "N";
if (addressDTO != null) {
deletedFlag = StateMapper.INSTANCE.stateToDeletedFlag(addressDTO.getStatus());
}
address.setDeletedFlag(deletedFlag);
}
#AfterMapping
default void setCountry(AddressDTO addressDTO, #MappingTarget Address address) {
String country = null;
if (addressDTO != null && addressDTO.getCountry() != null && !addressDTO.getCountry().isEmpty()) {
country = addressDTO.getCountry();
}
address.setISOCountryCode(country);
}
}
Here is an example of a Test:
AddressMapperTest.java
package com.myorg.ccr.simulator.b2b.messaging.mapping;
import com.myorg.myproject.model.AddressDTO;
import com.myorg.myproject.model.StateDTO;
import com.myorg.ccr.simulator.b2b.mapping.AddressMapper;
import com.myorg.ccr.simulator.b2b.messaging.mapping.helpers.AddressMappingHelper;
import com.myorg.xsd.b2b.upsertcustomer.Address;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.threeten.bp.OffsetDateTime;
import org.threeten.bp.format.DateTimeFormatter;
import static org.assertj.core.api.Assertions.assertThat;
#ExtendWith(SpringExtension.class)
#TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class AddressMapperTest {
private AddressMapper mapper = AddressMapper.INSTANCE;
#Test
public void xsdAddressToAddressTest() {
Address xsdAddress = new Address();
xsdAddress.setActiveFlag("Y");
xsdAddress.setDeletedFlag("N");
xsdAddress.setType("Billing");
xsdAddress.setPrimaryFlag("N");
xsdAddress.setExternalAddressId("15106794");
xsdAddress.setStreetAddress("Some Street Name 70 E/24");
xsdAddress.setStreetAddress2("Some Building info 123");
xsdAddress.setPOBox("08905");
xsdAddress.setCity("Białystok");
xsdAddress.setPostalCode("15-181");
xsdAddress.setISOCountryCode("PL");
xsdAddress.setRecipientLastName("Mustermann");
xsdAddress.setRecipientFirstName("Max");
xsdAddress.setRecipientSalutation("Mr.");
xsdAddress.setRecipientPhone("512341234");
xsdAddress.setAddressInvalidFlag("Y");
xsdAddress.setComments("A comment from the user.");
xsdAddress.setSourceCreatedDate("2016-06-14T21:19:33+02:00");
xsdAddress.setSourceUpdatedDate("2019-09-05T11:26:20+02:00");
AddressDTO address = mapper.addressToAddressDTO(xsdAddress);
assertThat(address.getId()).isNull();
assertThat(address.getStatus()).isNotNull();
assertThat(address.getStatus().getValue()).isNotNull();
assertThat(address.getStatus().getValue()).isEqualTo(1);
assertThat(address.getExternalAddressId()).isEqualTo("15106794");
assertThat(address.getAddressNumber()).isEqualTo(1);
assertThat(address.getStreet1()).isEqualTo("Some Street Name 70 E/24");
assertThat(address.getStreet2()).isEqualTo("Some Building info 123");
assertThat(address.getCity()).isEqualTo("Białystok");
assertThat(address.getPostalCode()).isEqualTo("15-181");
assertThat(address.getPostOfficeBox()).isEqualTo("08905");
assertThat(address.getCountry()).isNull(); //This may change
assertThat(address.getContactFullname()).isEqualTo("Max Mustermann");
assertThat(address.getSalutation()).isEqualTo("Mr.");
assertThat(address.getPhone()).isEqualTo("512341234");
assertThat(address.getComments()).isEqualTo("A comment from the user.");
assertThat(address.getSourceCreatedDate()).isEqualTo(OffsetDateTime.parse("2016-06-14T21:19:33+02:00",
DateTimeFormatter.ISO_OFFSET_DATE_TIME));
assertThat(address.getSourceUpdatedDate()).isEqualTo(OffsetDateTime.parse("2019-09-05T11:26:20+02:00",
DateTimeFormatter.ISO_OFFSET_DATE_TIME));
}
#Test
public void addressDTOToXSDAddressTest() {
AddressDTO addressDTO = new AddressDTO();
StateDTO state = new StateDTO();
state.setValue(1);
addressDTO.setStatus(state);
addressDTO.setExternalAddressId("15106794");
addressDTO.setAddressNumber(1);
addressDTO.setStreet1("Some Street Name 70 E/24");
addressDTO.setStreet2("Some Building info 123");
addressDTO.setPostOfficeBox("08905");
addressDTO.setCity("Białystok");
addressDTO.setPostalCode("15-181");
addressDTO.setCountry("PL");
addressDTO.setContactFullname("Max Mustermann");
addressDTO.setSalutation("Mr.");
addressDTO.setPhone("512341234");
addressDTO.setComments("A comment from the user.");
addressDTO.setSourceCreatedDate(OffsetDateTime.parse("2016-06-14T21:19:33+02:00",
DateTimeFormatter.ISO_OFFSET_DATE_TIME));
addressDTO.setSourceUpdatedDate(OffsetDateTime.parse("2019-09-05T11:26:20+02:00",
DateTimeFormatter.ISO_OFFSET_DATE_TIME));
Address address = mapper.addressDTOToAddress(addressDTO);
assertThat(address.getActiveFlag()).isEqualTo("Y"); //This may change
assertThat(address.getDeletedFlag()).isEqualTo("N"); //This may change
assertThat(address.getExternalAddressId()).isEqualTo("15106794");
assertThat(address.getPrimaryFlag()).isEqualTo("Y");
assertThat(address.getStreetAddress()).isEqualTo("Some Street Name 70 E/24");
assertThat(address.getStreetAddress2()).isEqualTo("Some Building info 123");
assertThat(address.getCity()).isEqualTo("Białystok");
assertThat(address.getPostalCode()).isEqualTo("15-181");
assertThat(address.getPOBox()).isEqualTo("08905");
assertThat(address.getISOCountryCode()).isEqualTo("PL"); //This may change
assertThat(address.getRecipientFirstName()).isEqualTo("Max Mustermann");
assertThat(address.getRecipientSalutation()).isEqualTo("Mr.");
assertThat(address.getRecipientPhone()).isEqualTo("512341234");
assertThat(address.getComments()).isEqualTo("A comment from the user.");
assertThat(address.getSourceCreatedDate()).isEqualTo("2016-06-14T21:19:33+02:00");
assertThat(address.getSourceUpdatedDate()).isEqualTo("2019-09-05T11:26:20+02:00");
}
#Test
public void dynamicXSDAddressToAddressDTOTest() {
AddressMappingHelper mappingHelper = new AddressMappingHelper();
while (mappingHelper.hasNext()) {
mappingHelper.nextXSDAddress();
Address xsdAddress = mappingHelper.getExpectedAddress();
AddressDTO address = mapper.addressToAddressDTO(xsdAddress);
AddressDTO expectedAddress = mappingHelper.getExpectedAddressDTO();
assertThat(address).usingRecursiveComparison().isEqualTo(expectedAddress);
}
}
#Test
public void dynamicAddressDTOToXSDAddressTest() {
AddressMappingHelper mappingHelper = new AddressMappingHelper();
while (mappingHelper.hasNext()) {
mappingHelper.nextXSDAddress();
AddressDTO addressDTO = mappingHelper.getExpectedAddressDTO();
Address address = mapper.addressDTOToAddress(addressDTO);
Address expectedAddress = mappingHelper.getExpectedAddressFromDTO();
System.out.println(address);
System.out.println(expectedAddress);
assertThat(address).usingRecursiveComparison().isEqualTo(expectedAddress);
}
}
}
Here is the build.gradle file:
build.gradle
buildscript {
ext {
springBootVersion = '2.1.5.RELEASE'
jmsVersion = '2.0.1'
jaxbApiVersion = '2.2.7'
flywayVersion = '5.2.1'
// tests
junitJuniper = '5.1.1'
junitGradlePlatformVersion = '1.1.0'
assertJCoreVersion = '3.14.0'
mapstructVersion = "1.3.0.Final"
swaggerCodgenVersion = '3.0.13'
jacksonThreetenVersion = '2.6.4'
}
repositories {
mavenCentral()
jcenter()
}
dependencies {
classpath "org.springframework.boot:spring-boot-gradle-plugin:$springBootVersion"
}
}
apply plugin: 'idea'
apply plugin: 'java'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
apply plugin: "checkstyle"
group = 'com.myorg.ccr'
sourceCompatibility = '1.8'
targetCompatibility = '1.8'
repositories {
mavenCentral()
maven {
credentials {
username = "$mavenUser"
password = "$mavenPassword"
}
url "https://myorg.jfrog.io/myorg/libs-snapshot"
}
maven {
credentials {
username = "$mavenUser"
password = "$mavenPassword"
}
url "https://myorg.jfrog.io/myorg/libs-release"
}
}
sourceSets {
main {
java {
srcDir 'src/schema'
}
}
}
configurations {
jaxb_generateSources
}
dependencies {
annotationProcessor 'org.projectlombok:lombok:1.18.6'
annotationProcessor "org.springframework.boot:spring-boot-configuration-processor"
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-security', version: springBootVersion
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: springBootVersion
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: springBootVersion
// https://mvnrepository.com/artifact/javax.jms/javax.jms-api
implementation group: 'javax.jms', name: 'javax.jms-api', version: jmsVersion
implementation group: 'org.springframework', name: 'spring-jms', version: '5.1.9.RELEASE'
implementation group: 'com.tibco', name: 'tibjms', version: '8.2.1'
implementation group: 'com.myorg.ccr.client', name: 'customer-client', version: '1.1.0-SNAPSHOT'
compile group: 'com.myorg.login', name: 'login-lib-java-spring', version: '1.5.0-SNAPSHOT'
runtimeOnly group: 'org.postgresql', name: 'postgresql'
runtimeOnly group: 'com.h2database', name: 'h2'
implementation group: 'org.flywaydb', name: 'flyway-core', version: flywayVersion
testImplementation "org.junit.jupiter:junit-jupiter-api:$junitJuniper"
testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:$junitJuniper"
testCompile "org.assertj:assertj-core:$assertJCoreVersion"
testCompile("org.springframework.boot:spring-boot-starter-test")
testCompile("org.springframework.security:spring-security-test")
jaxb_generateSources(
[group: 'com.sun.xml.bind', name: 'jaxb-xjc', version: jaxbApiVersion],
[group: 'com.sun.xml.bind', name: 'jaxb-impl', version: jaxbApiVersion],
)
compileOnly 'org.projectlombok:lombok:1.18.6'
compileOnly "org.springframework.boot:spring-boot-configuration-processor"
implementation "org.mapstruct:mapstruct:${mapstructVersion}"
annotationProcessor "org.mapstruct:mapstruct-processor:${mapstructVersion}"
// If you are using mapstruct in test code
testAnnotationProcessor "org.mapstruct:mapstruct-processor:${mapstructVersion}"
compile "io.swagger.codegen.v3:swagger-codegen-maven-plugin:$swaggerCodgenVersion"
compile "com.github.joschi.jackson:jackson-datatype-threetenbp:$jacksonThreetenVersion"
}
clean {
delete 'src/schema'
}
task jaxb_generateSources {
System.setProperty('javax.xml.accessExternalSchema', 'all')
def jaxbTargetDir = file("src/schema")
doLast {
ext.generateSources = { packageName, xsdSchemaLocation ->
ant.taskdef(
name: 'xjc',
classname: 'com.sun.tools.xjc.XJCTask',
classpath: configurations.jaxb_generateSources.asPath
)
ant.jaxbTargetDir = jaxbTargetDir
ant.xjc(
destdir: '${jaxbTargetDir}',
package: packageName,
schema: xsdSchemaLocation,
encoding: 'UTF-8'
)
}
jaxbTargetDir.mkdirs()
// b2c
generateSources('com.myorg.xsd.upsertcustomer', 'src/main/resources/b2c.xsd/doAsyncUpsertCustomer_BDM_DST.xsd')
// b2b
generateSources('com.myorg.xsd.b2b.upsertcustomer', 'src/main/resources/b2b/xsd/doAsyncUpsertAccount_BDM_DST.xsd')
}
}
compileJava {
dependsOn jaxb_generateSources
}
test {
useJUnitPlatform()
// TODO: Is actual an integration and no unit test
exclude '**/ContactControllerTest.class'
}
task integrationTest(type: Test) {
useJUnitPlatform()
description = 'Runs the integration tests.'
group = 'verification'
include '**/ContactControllerTest.class'
}
tasks.withType(Checkstyle) {
exclude '**/b2bkam/**'
}
checkstyle {
config = rootProject.resources.text.fromFile("${rootDir}/config/checkstyle/checkstyle_ccr-simulator_v1.xml")
toolVersion '8.11'
}
Thank you in advance,
Aitor

Gradle: How to init SourceTask's property ‘source’ with extension property?

My plugin registers an extension and some custom task that inherited from org.gradle.api.tasks.SourceTask.
class MyPlugin implements Plugin<Project> {
private final Instantiator instantiator
private final FileResolver fileResolver
#Inject
MyPlugin (Instantiator instantiator, FileResolver fileResolver) {
this.instantiator = instantiator
this.fileResolver = fileResolver
}
void apply(Project project) {
MyPluginExtension extension = project.extensions.create("myPlugin", MyPluginExtension, project, instantiator, fileResolver)
project.tasks.create('doSomething', MyCustomTask) {}
}
}
class MyPluginExtension {
final MySourceSetContainer source
MyPluginExtension(Project project, Instantiator instantiator, FileResolver fileResolver) {
source = instantiator.newInstance(ImplMySourceSetContainer, project, instantiator, fileResolver)
}
void source(Closure closure) {
ConfigureUtil.configure(closure, source)
}
}
class MyCustomTask extends SourceTask {
#TaskAction
void act() {
// something
}
}
And now, if I configure build script:
myPlugin {
source{
main {
something {
srcDirs "src/main/resources"
}
}
}
}
doSomething {
source = myPlugin.source.main.something.asFileTree
}
- All works fine. But I want to initialize task property source by value from MyPluginExtension.
source = extension.source.findAll().inject(project.files().asFileTree, { result, item -> result + item.html.asFileTree })
I can't extract extension property at the execution phase as it described in the userguide (https://docs.gradle.org/4.2.1/userguide/custom_plugins.html#sec:mapping_extension_properties_to_task_properties), because getter for source that declared in superclass org.gradle.api.tasks.SourceTask marked with annotation #org.gradle.api.tasks.SkipWhenEmpty and task will be skipped.
How can I initialize task's property with value from extension before execution phase?
Thx.
I'm not sure that I fully understand what you are doing but you could likely use a closure to delay evaluation. See Project.files(Object...)
Eg:
doSomething {
def myClosure = {
extension.source.findAll().inject(project.files().asFileTree, { result, item -> result + item.html.asFileTree })
}
source = files(myClosure)
}
Resolved by wrapping source init in closure:
class MyPlugin implements Plugin<Project> {
// ...
void apply(Project project) {
MyPluginExtension extension = project.extensions.create("myPlugin", MyPluginExtension, project, instantiator, fileResolver)
project.tasks.create('doSomething', MyCustomTask) { task ->
task.source = {
extension.source.findAll().inject(new HashSet<File>(), { result, item -> result + item.html.srcDirs })
}
}
}
}

How to access Gradle `project` from `buildSrc`?

I have the following in buildSrc:
class MyClass {
def doSomething() {
final familyMembers = project.configurations['compile'].allDependencies.collect { dep ->
dep.name
}
}
but when I try to use it in build.gradle:
task 'do-something' << {
final myObject = new MyClass()
myObject.doSomething()
}
the following error is emitted:
* What went wrong:
Execution failed for task ':my-project:do-something'.
> No such property: project for class: MyClass
How do I get project to be visible within MyClass?
You'll have to pass project as a parameter to MyClass.
For example, declare a constructor and a member variable:
class MyClass {
private Project project
MyClass(Project project) {
this.project = project
}
def doSomething() {
final familyMembers = project.configurations['compile'].allDependencies.collect { dep ->
dep.name
}
}
and then use it from your project as such:
task 'do-something' << {
final myObject = new MyClass(project)
myObject.doSomething()
}

Resources