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

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?

Related

Gradle: Set same property to all compile*Kotlin tasks

We have a Gradle build, with these blocks:
compileKotlin {
kotlinOptions {
jvmTarget = 11
}
}
compileTestKotlin {
kotlinOptions {
jvmTarget = 11
}
}
compileTestIntegrationKotlin {
kotlinOptions {
jvmTarget = 11
}
}
Is there a way to apply kotlinOptions to all of these tasks?
Earlier I saw something along the lines of
allTasks.withType("compile") { ... }
But I can't find any documentation for that. Where is it? Thanks.
As shown here: https://kotlinlang.org/docs/mpp-configure-compilations.html#configure-all-compilations
You should be able to do:
kotlin {
targets.all {
compilations.all {
kotlinOptions {
jvmTarget = 11
}
}
}
}

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

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

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 })
}
}
}
}

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());
}
}

Resources