Run/Debug JUnit 5 Tests using Gradle and Mapstruct - spring

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

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?

Use gradle plugin to configure another gradle plugin

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

Spring data neo4j

I'm trying to use Neo4j but i still have some problems. When i try to run a test to create a node, i have an exception saying that is impossible to autowired the repository interface.
this is my configuration :
build.gradle :
buildscript {
ext {
springBootVersion = '1.2.4.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
classpath("io.spring.gradle:dependency-management-plugin:0.5.1.RELEASE")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'spring-boot'
apply plugin: 'io.spring.dependency-management'
jar {
baseName = 'demo'
version = '0.0.1-SNAPSHOT'
}
sourceCompatibility = 1.7
targetCompatibility = 1.7
repositories {
mavenCentral()
}
dependencies {
compile("org.springframework.boot:spring-boot-starter")
testCompile("org.springframework.boot:spring-boot-starter-test")
compile 'org.springframework.data:spring-data-neo4j:3.3.0.RELEASE'
compile("org.hibernate:hibernate-validator")
compile 'org.neo4j:neo4j:2.2.3'
compile 'javax.annotation:javax.annotation-api:1.2'
}
eclipse {
classpath {
containers.remove('org.eclipse.jdt.launching.JRE_CONTAINER')
containers 'org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7'
}
}
task wrapper(type: Wrapper) {
gradleVersion = '2.3'
}
applicationContext.xml :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:neo4j="http://www.springframework.org/schema/data/neo4j"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/data/neo4j http://www.springframework.org/schema/data/neo4j/spring-neo4j-3.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<context:annotation-config />
<context:component-scan base-package="com.****.pocneo4j.service.impl" />
<neo4j:config storeDirectory="/data"
base-package="com.****.pocneo4j.domain.entity" />
<neo4j:repositories base-package="com.****.pocneo4j.domain.repository" />
<tx:annotation-driven />
</beans>
My entity :
package com.****.pocneo4j.domain.entity;
import org.springframework.data.neo4j.annotation.GraphId;
import org.springframework.data.neo4j.annotation.NodeEntity;
#NodeEntity
public class QuestionNode {
#GraphId
private Long idQuestionNode;
private int idQuestionRef;
public Long getIdQuestionNode() {
return idQuestionNode;
}
public int getIdQuestionRef() {
return idQuestionRef;
}
public void setIdQuestionRef(int idQuestionRef) {
this.idQuestionRef = idQuestionRef;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((idQuestionNode == null) ? 0 : idQuestionNode.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
QuestionNode other = (QuestionNode) obj;
if (idQuestionNode == null) {
if (other.idQuestionNode != null)
return false;
} else if (!idQuestionNode.equals(other.idQuestionNode))
return false;
return true;
}
#Override
public String toString() {
return "QuestionNode [idQuestionNode=" + idQuestionNode
+ ", idQuestionRef=" + idQuestionRef + "]";
}
}
Repository
package com.****.pocneo4j.domain.repository;
import org.springframework.data.neo4j.repository.GraphRepository;
import com.****.pocneo4j.domain.entity.QuestionNode;
public interface QuestionNodeRepository extends GraphRepository<QuestionNode>{
}
My service :
package com.****.pocneo4j.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.****.pocneo4j.domain.entity.QuestionNode;
import com.****.pocneo4j.domain.repository.QuestionNodeRepository;
import com.****.pocneo4j.service.interf.QuestionNodeIService;
#Service("QuestionNodeManager")
public class QuestionNodeService implements QuestionNodeIService {
#Autowired
private QuestionNodeRepository questionNodeRepository;
#Override
public QuestionNode create(QuestionNode questionNode){
return questionNodeRepository.save(questionNode);
}
}
and here my test
package com.****.pocneo4j.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.****.pocneo4j.domain.entity.QuestionNode;
import com.****.pocneo4j.service.interf.QuestionNodeIService;
public class Test01 {
#Test
public void test() {
#SuppressWarnings("resource")
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"applicationContext.xml");
QuestionNodeIService questionNodeManager = (QuestionNodeIService) ctx
.getBean("QuestionNodeManager");
QuestionNode testQuestionNode = new QuestionNode();
testQuestionNode.setIdQuestionRef(90);
questionNodeManager.create(testQuestionNode);
System.out.println("NODE ID = " + testQuestionNode.getIdQuestionNode()
+ " || QUESTION REF ID = "
+ testQuestionNode.getIdQuestionRef());
}
}

How can I get a dependency's version in the current pom.xml for maven-enforcer-plugin?

I'm trying to write an maven-enforcer rule, which checks that that project uses dependency management.
But I've got trouble to get the version which is written in the current project's pom.xml. I thought DependencyNode#getPremanagedVersion() would provide it, but it looks like it's returning a version which is set by a dependency (i.e. log4j is set in jbossall-client).
How can I get a dependency's version in the current pom.xml?
package org.example;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.artifact.metadata.ArtifactMetadataSource;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.ArtifactCollector;
import org.apache.maven.enforcer.rule.api.EnforcerRule;
import org.apache.maven.enforcer.rule.api.EnforcerRuleException;
import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper;
import org.apache.maven.project.MavenProject;
import org.apache.maven.shared.dependency.tree.DependencyNode;
import org.apache.maven.shared.dependency.tree.DependencyTreeBuilder;
import org.opencredo.maven.plugins.enforcer.utils.DefaultDependencyTreePrinter;
import com.oneandone.access.preclearing.AbstractNonCacheableEnforcerRule;
public class ForceDependencyManagement extends AbstractNonCacheableEnforcerRule implements EnforcerRule {
private String message = "";
private MavenProject project;
private ArtifactRepository localRepository;
private ArtifactFactory artifactFactory;
private ArtifactMetadataSource artifactMetadataSource;
private ArtifactCollector artifactCollector;
private DependencyTreeBuilder dependencyTreeBuilder;
private void init(EnforcerRuleHelper helper) throws EnforcerRuleException {
try {
project = (MavenProject) helper.evaluate("${project}");
localRepository = (ArtifactRepository) helper.evaluate("${localRepository}");
artifactFactory = (ArtifactFactory) helper.getComponent(ArtifactFactory.class);
artifactCollector = (ArtifactCollector) helper.getComponent(ArtifactCollector.class);
artifactMetadataSource = (ArtifactMetadataSource) helper.getComponent(ArtifactMetadataSource.class);
dependencyTreeBuilder = (DependencyTreeBuilder) helper.getComponent(DependencyTreeBuilder.class);
} catch (Exception eee) {
throw new EnforcerRuleException("Unable to retrieve the rule dependencies: ", eee);
}
}
public void execute(EnforcerRuleHelper helper) throws EnforcerRuleException {
init(helper);
DependencyNode rootNode = buildDependencyTree();
if (rootNode != null) {
Set found = new HashSet();
Iterator iter = rootNode.iterator();
System.out.println("Dependencies: ");
while (iter.hasNext()) {
DependencyNode node = (DependencyNode) iter.next();
if (StringUtils.isNotEmpty(node.getPremanagedVersion())) {
found.add(node);
}
}
if (found.size() > 0) {
fail(found);
}
}
}
protected DependencyNode buildDependencyTree() {
try {
DependencyNode rootNode =
dependencyTreeBuilder.buildDependencyTree(project, localRepository, artifactFactory,
artifactMetadataSource, null, artifactCollector);
return rootNode;
} catch (Exception e) {
throw new RuntimeException("Failed to build dependency tree", e);
}
}
private void fail(Set found) throws EnforcerRuleException {
Iterator iter;
StringBuffer fullMessage = new StringBuffer();
if (StringUtils.isNotEmpty(message)) {
fullMessage.append(message);
} else {
fullMessage.append("Found artifact without dependency management:");
}
fullMessage.append("\n");
iter = found.iterator();
while (iter.hasNext()) {
DependencyNode node = (DependencyNode) iter.next();
Artifact artifact = node.getArtifact();
fullMessage.append(" " + artifact.getGroupId() + ":" + artifact.getArtifactId() + " is set to version "
+ node.getPremanagedVersion() + "\n");
getTreePrinter().printDependencyTree(fullMessage, artifact, 4);
}
throw new EnforcerRuleException(fullMessage.toString());
}
private DefaultDependencyTreePrinter getTreePrinter() {
return new DefaultDependencyTreePrinter(project, localRepository, artifactFactory, artifactMetadataSource,
artifactCollector, dependencyTreeBuilder);
}
public boolean isCacheable() {
return false;
}
public String getCacheId() {
return null;
}
public boolean isResultValid(EnforcerRule cachedRule) {
return false;
}
}
This should do it
MavenProject project = (MavenProject) helper.evaluate("${project}");
List dependencies = project.getDependencies();
From there just iterate throught the list of dependencies and call .getVersion()
for (int i = 0; i < project.getDependencies().size(); i++) {
String version = project.getDependencies().get(i).getVersion();
}
You can also get to the dependency management info from the project object

Resources