I have followed this guide:
http://www.gradle.org/docs/current/userguide/custom_plugins.html
to create a standalone gradle plugin with the following structure/files:
my-gradle-plugin
> src
> main
> java
> com
> mygroup
> MyGradlePlugin.groovy
> build.gradle
> settings.gradle
build.gradle :
apply plugin: 'groovy'
dependencies {
compile gradleApi()
groovy localGroovy()
}
apply plugin: 'maven'
repositories {
mavenCentral()
}
group = 'com.mygroup'
version = '1.0.0-SNAPSHOT'
MyGradlePlugin.groovy :
package com.mygroup
import org.gradle.api.*
class MyGradlePlugin implements Plugin<Project> {
void apply(Project project) {
print " project.name " + project.name + "\n"
print " project.dependencies " + project.dependencies + "\n"
// How do we iterate each dependency and print artifactId, group, version??
// project.dependencies.each {
// compile(it) {
// print it.next()
// print it.name
// }
// }
project.configurations.each {
print it.dump()
}
}
}
In another project I use/apply this plugin:
apply plugin: 'java'
apply plugin: 'maven'
apply plugin: 'eclipse'
repositories {
mavenLocal()
}
buildscript {
repositories {
mavenLocal()
}
dependencies {
classpath group: 'com.mygroup', name: 'my-gradle-plugin', version: '1.0.0-SNAPSHOT'
}
}
dependencies {
compile group: 'commons-codec', name: 'commons-codec', version: '1.4'
compile group: 'commons-beanutils', name: 'commons-beanutils', version: '1.7.0'
}
install.doLast {
apply plugin: 'my-gradle-plugin'
}
But how do I iterate the commons dependencies from the apply method in MyGradlePlugin.groovy and print their coordinates (artifactId, groupId, version)?
I know this is an old question but since there is not a selected answer I'll throw in an example that I have used. This is based on the example in section 49.8.2.2 of the gradle docs.
I'm using it to do custom dependency resolution, but you can do whatever you'd like inside the dependency iteration. Note that this works because its passing a closure that is executed after the configuration phase.
Plugin code:
package com.overtherainbow
import org.gradle.api.Project
import org.gradle.api.Plugin
import org.gradle.api.artifacts.DependencyResolveDetails
class DefaultVersionPlugin implements Plugin<Project> {
// This is where dependency versions are defined
def defaultVersionsMap = [
'javax.servlet:servlet-api' : '2.5',
'log4j:log4j' : '1.2.16']
void apply(Project project) {
project.configurations.all {
resolutionStrategy.eachDependency {
DependencyResolveDetails details -> resolveDependencyVersion(project, details)
}
}
}
def resolveDependencyVersion(Project project, DependencyResolveDetails details) {
if (details.requested.version == 'default') {
def version = resolveDefaultVersion(project, details.requested.group, details.requested.name)
details.useVersion version
}
}
def resolveDefaultVersion(Project project, String group, String name) {
project.logger.debug("Resolving default dependency for $group:$name")
println "Resolving default dependency for $group:$name"
defaultVersionsMap["$group:$name"]
}
}
The problem is that dependency graph is only available after project is fully evaluated. That's why you can't rely on that directly in the apply method. You have to postpone the execution using the afterEvaluate method. The following code will do the trick:
class MyGradlePlugin implements Plugin<Project> {
void apply(Project project) {
project.afterEvaluate {
println " Project:" + project.name
project.configurations.each { conf ->
println " Configuration: ${conf.name}"
conf.allDependencies.each { dep ->
println " ${dep.group}:${dep.name}:${dep.version}"
}
}
}
}
}
UPDATE: Following question updates and discussions in the comments and chat you can also do the following:
class MyGradlePlugin implements Plugin<Project> {
void apply(Project project) {
project.tasks.findByName('install')?.doLast {
...
}
}
}
Related
I write a custom annotation Processor, I hope get ast tree in process method in eclipse ecj compiler:
private JavacProcessingEnvironment env;
private BaseProcessingEnvImpl eclipseEnv;
#Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (!annotations.isEmpty()) {
Set<? extends Element> elementsAnno = roundEnv.getElementsAnnotatedWith(xxxxAnnoClass.class);
if (env != null) { // javac
Context context = env.getContext();
Trees trees = Trees.instance(env);
elementsAnno.forEach(e -> {
JCTree tree = ((JavacTrees) trees).getTree(e);
});
new TreeTranslator().translate(tree);
}else { // eclipse ecj
// how to write the code equivalent of javac
}
}
}
I have a problem when I try to use a MongoRepository. This is my Document class:
package model
import org.springframework.data.annotation.Id
import org.springframework.data.mongodb.core.mapping.Document
#Document
class Product (#Id val name: String, var desc: String, var price: Double) {
var pictureCategory: String? = null
}
This is the repository:
package model.repositories
import model.Product
import org.springframework.data.mongodb.repository.MongoRepository
import org.springframework.stereotype.Repository
#Repository
interface ProductRepository : MongoRepository <Product, String>
and this is the file where I have the compile error:
package controllers
import model.Product
import model.repositories.ProductRepository
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
#Controller
#RequestMapping("/product")
class ProductController {
#PostMapping("")
fun addProduct(#RequestBody newProduct: Product){
ProductRepository.save() //Unresolved reference: save <----------------------
}
}
I tried to performe and invalidate/restart but nothing is changed.
This is my build.gradle.kts file:
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
id("org.springframework.boot") version "2.4.3"
id("io.spring.dependency-management") version "1.0.11.RELEASE"
kotlin("jvm") version "1.4.30"
kotlin("plugin.spring") version "1.4.30"
kotlin("plugin.jpa") version "1.4.30"
}
group = "com.example"
version = "1.0.0"
java.sourceCompatibility = JavaVersion.VERSION_11
repositories {
mavenCentral()
}
dependencies {
implementation("org.springframework.boot:spring-boot-starter-data-mongodb")
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
implementation("org.jetbrains.kotlin:kotlin-reflect")
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
testImplementation("org.springframework.boot:spring-boot-starter-test")
}
tasks.withType<KotlinCompile> {
kotlinOptions {
freeCompilerArgs = listOf("-Xjsr305=strict")
jvmTarget = "11"
}
}
tasks.withType<Test> {
useJUnitPlatform()
}
Maybe some dependencies that I have to add?
You are supposed to inject your repository in the REST controller, not using the static "save" method.
See : https://spring.io/guides/tutorials/rest/ for example.
I am trying to run a springboot application on embedded Tomcat server in Eclipse. The project is added successfully to the server but it never starts.
My application code is below:
import java.util.Properties;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;
import org.springframework.boot.Banner;
#SpringBootApplication
#ImportResource("classpath:simple-camel.xml")
public class CamelApplication {
private static final String DEFAULT_XML_ROUTE_CONFIG_FILES = "classpath:/routes/*.xml";
public static void main(String[] args) {
System.out.println("********************* inside the project ******************");
SpringApplication app = new SpringApplication(CamelApplication.class);
app.setDefaultProperties(getDefaultProperties());
app.run(args);
}
private static Properties getDefaultProperties() {
Properties props = new Properties();
props.setProperty("camel.springboot.main-run-controller", "true");
return props;
}
}
My build.gradle is below:
plugins {
id 'groovy'
id 'java'
id "org.springframework.boot" version "2.2.6.RELEASE"
}
group 'com.firas'
version '1.0-SNAPSHOT'
apply plugin: "org.springframework.boot"
apply plugin: "java"
repositories {
mavenCentral()
}
dependencies {
compile "org.apache.camel:camel-bom:2.25.0"
compile "org.apache.camel:camel-core:2.25.0"
compile "org.apache.camel:camel-spring-boot-dependencies:2.25.0"
compile "org.apache.camel:camel-spring-boot-starter:2.25.0"
compile "org.springframework:spring-aop:4.0.4.RELEASE"
compile "org.springframework:spring-context:4.0.4.RELEASE"
compile "org.springframework:spring-tx:4.0.4.RELEASE"
compile "org.apache.camel.springboot:camel-timer-starter:2.25.0"
compile "org.springframework.boot:spring-boot-starter-tomcat:2.2.6.RELEASE"
testCompile group: 'junit', name: 'junit', version: '4.13'
}
springBoot {
mainClassName = 'CamelApplication'
}
bootJar {
mainClassName = 'CamelApplication'
manifest {
attributes 'Start-Class': 'CamelApplication'
}
}
and below is a screen shot of my Deployment Assembly configuration:
Any hints or guidance on how to fix it? I am not seeing any errors in the log so I am flying blind here.
I tried to setup gradle in eclipse Luna for a simple spring boot application, but none of the jars are downloaded. Can anyone give me an idea of what I'm missing ?
I ran gradle clean build in the command line and it compiles successfully:
This is the content of my build.gradle file :
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.4.1.RELEASE")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'spring-boot'
jar {
baseName = 'sample'
version = '0.1.0'
}
repositories {
mavenCentral()
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
dependencies {
compile("org.springframework.boot:spring-boot-starter-web")
}
This is the content of the class with the controller:
package sample;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class SampleController {
#RequestMapping("/sample")
public String sampleIt(){
return "Hello! Welcome to Spring Boot Sample. ";
}
}
This is the class with the main function :
package sample;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
#SpringBootApplication
public class SampleApplication {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(SampleApplication.class, args);
System.out.println(ctx.getDisplayName());
System.out.println("This is my first Spring Boot Example");
}
}
Answer from the comment:
It is necessary to install the gradle plugin and import the gradle project afterwards. (Don't forget to click the 'Build Model' button)
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.google.guava:guava:18.0'
}
}
apply plugin: LolPlugin
class LolPlugin implements Plugin<Project> {
public void apply(Project p) {
p.buildscript.dependencies.each {
println it
}
}
}
In this example, you can try to get dependencies name inside custom plugin class.
But it's different between contents of output and the expected .
I expect that,
'com.google.guava:guava:18.0'
But output is
org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependenciesHandler_Decorate#174b0a8
Almost duplicate of this question: How to iterate gradle dependencies in custom gradle plugin?
Short answer:
class LolPlugin implements Plugin<Project> {
public void apply(Project p) {
p.buildscript.configurations.each {
it.allDependencies.each {
println "${it.group}:${it.name}:${it.version}"
}
}
}
}