Define Constants in Gradle in Java Project - java

I am building a Spring Boot project and i want to define some constants in gradle. I used to be an Android developer, and in Android you can define it with buildConfigField. How can I do it in Java project?
Is there a tool that is equivalent to the following?
android {
buildTypes {
debug {
buildConfigField "String", "BASE_URL", "http://debug.server.com"
}
release {
buildConfigField "String", "BASE_URL", "http://release.server.com"
}
}
}

If you are using Gradle as your building tool, you can define Environment Variables inside you build.gradle file, using the following syntax:
buildscript {
repositories {
if (System.getenv("RESOLVE_LOCAL")) {
maven { url "$indexUrl/resolver-grails3" }
} else {
maven { url "$indexLocalUrl/resolver-grails3" }
}
}
dependencies {
classpath 'build-info-extractor:build-info-extractor-gradle:3.1.1'
classpath group: 'org._10ne.gradle', name: 'rest-gradle-plugin, version: '0.3.1'
}
}
apply plugin: 'org.10ne.rest'

Related

Gradle Not Finding Method Implementation for Arguments

I am trying to build a simple maven library and I can't get it to build. I am using Gradle Groovy and Kotlin Multiplatform Library in IntelliJ IDEA.
I haven't even been able to begin coding since my dependencies wont load. I am very new to all this so bare with me.
This is my build.gradle
plugins {
id 'org.jetbrains.kotlin.multiplatform' version '1.7.10'
}
group = 'me.me'
version = '1.0-SNAPSHOT'
repositories {
mavenCentral()
}
dependencies{
implementation platform("io.cucumber:cucumber-bom:7.1.0")
implementation 'io.cucumber:cucumber-java'
implementation 'io.cucumber:cucumber-junit-platform-engine'
implementation 'io.cucumber:cucumber-junit'
implementation 'io.cucumber:cucumber-spring'
implementation 'com.googlecode.json-simple:json-simple:1.1.1'
}
kotlin {
jvm {
compilations.all {
kotlinOptions.jvmTarget = '1.8'
}
withJava()
testRuns["test"].executionTask.configure {
useTestNG()
}
}
sourceSets {
commonMain {
}
commonTest {
dependencies {
implementation kotlin('test')
}
}
}
}
and this is the error I am getting
Build file '/Users/Me/Documents/GitHub/Project-Tools/build.gradle' line: 13
A problem occurred evaluating root project 'Project-Tools'.
> Could not find method implementation() for arguments
[DefaultExternalModuleDependency{group='io.cucumber', name='cucumber-bom', version='7.1.0', configuration='default'}]
on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.
I even tried commenting out each dependency one at a time so see if any work and none did
EDIT: Also I am on a Mac

is it possible to force java module dependencies to use specify version [duplicate]

I have a distributes projects with different sub-projects and I want to accomplish the following:
(root)
client
module A
module B
module C
model
I want to put
protoc {
artifact = 'com.google.protobuf:protoc:3.5.0'
}
plugins {
grpc {
artifact = "io.grpc:protoc-gen-grpc-java:1.7.0"
}
}
generateProtoTasks {
all()*.plugins {
grpc {}
}
} }
dependencies {
compile "com.google.api.grpc:proto-google-common-protos:1.0.0"
compile "io.grpc:grpc-netty:1.7.0"
compile "io.grpc:grpc-protobuf:1.7.0"
compile "io.grpc:grpc-stub:1.7.0"
}
for module A, B and C.
For now I have the following in my root build.gradle
subprojects{
apply plugin: 'java'
sourceCompatibility = 1.8
group 'project'
version '0.0.1-SNAPSHOT'
jar {
manifest {
attributes 'Main-Class': "com.project.${project.name}.App"
}
doFirst {
from { configurations.runtime.collect { it.isDirectory() ? it : zipTree(it) } }
}
}
repositories {
mavenCentral()
mavenLocal()
}
dependencies {
testCompile 'junit:junit:4.12'
testCompile 'org.mockito:mockito-core:1.9.5'
}
}
So every sub-project use java plugin, and has the defines dependencies and jar task.
How can I only put the first block for some sub-projects ?
I tried using a variable like in Multi-project Builds - Gradle but I couldn't access it in subprojects block.
Thank you in advance. I'm really interested in using Gradle correctly and it's a bit hard to get into it outside of simple Android/Java projects. Feel free to include any documentations I should read :)
Edit:
Thank you. I wouldn't have posted here if I hadn't search before. Apparently I was missing the keyword "subset" who would have gave me the solution you linked.
A solution is described here: https://discuss.gradle.org/t/configure-only-subset-of-subprojects/5379/3
You can run configure() with a list of projects.
project.ext {
subprojectList = subprojects.findAll{
it.name == 'subprojectA' ||
it.name == 'subprojectB' ||
it.name == 'subprojectC'
}
}
configure(project.subprojectList) {
// insert your custom configuration code
}
or
configure([project(':a'), project(':b'), project(':c')]) {
// configuration
}

Generate Maven "provided" dependency in pom.xml from Gradle "compileOnly"

If I understand correctly, Gradle's compileOnly dependency corresponds to Gradle's older provided, and at the same time, Maven POM's provided. It works perfectly in the Gradle world.
But, compileOnly does not generate any provided dependency in pom.xml generated by maven-publish.
We are publishing a Maven artifact to Maven Central, using Gradle. We would like to declare provided explicitly in the published pom.xml from Gradle's compileOnly.
Does anyone know if there is any simple way to do that? Or, do we need to write our own Gradle scripting in :
publishing {
publications {
maven(MavenPublication) {
pom {
/* Our own Gradle scripting to declare provided dependencies. */
}
}
}
}
I know we can tweak it by scripting dirty like below, but we basically don't want to "script" in build.gradle as far as possible.
publishing {
publications {
maven(MavenPublication) {
pom {
withXml {
project.configurations.compileOnly.allDependencies.each { dependency ->
asNode().dependencies[0].appendNode("dependency").with {
it.appendNode("groupId", dependency.group)
it.appendNode("artifactId", dependency.name)
it.appendNode("version", dependency.version)
it.appendNode("scope", "provided")
}
}
}
}
}
}
}
I think scripting is the way to go... you can create a method och pass the pom e.g
publishing {
publications {
mavenDependencyList(MavenPublication) {
fixDependencyScope(pom)
}
}
}
void fixDependencyScope(pom) {
pom.withXml {
asNode().dependencies.'*'.findAll() {
it.scope.text() == 'compileOnly' && project.configurations.compile.allDependencies.find { dep ->
dep.name == it.artifactId.text()
}
}.each() {
it.scope*.value = 'provided'
}
}
}

Gradle multiple subproject with different spring boot plugin

I have multi project build structure and spring boot is applied from the parent to all subprojects. Here's the parent build.gradle
buildscript {
repositories {
maven {
url 'http://someurl.com/repository/MavenRepositoryGroup/'
}
}
dependencies {
classpath "org.springframework.boot:spring-boot-gradle-plugin:1.5.8.RELEASE"
}
}
subprojects {
apply plugin: 'java'
apply plugin: 'maven'
apply plugin: 'eclipse'
apply plugin: 'war'
apply plugin: 'org.springframework.boot'
..
..
..
}
}
Among multiple subprojects, I have a requirement to upgrade just one subproject to spring boot 2 version. How to do it?
It's pretty easy, just declare plugins in subprojects directly, where they are used. BTW, consider using new plugins DSL instead of apply. Take a look at a demo project I created for you. Here are the most interesting parts:
settings.gradle:
rootProject.name = "so53381565"
enableFeaturePreview("IMPROVED_POM_SUPPORT")
include(":a")
include(":b")
include(":c")
build.gradle:
subprojects {
apply plugin: "java"
repositories {
jcenter()
}
}
wrapper {
gradleVersion = "4.10.2"
distributionType = Wrapper.DistributionType.ALL
}
a/build.gradle:
plugins {
id "org.springframework.boot" version "1.5.8.RELEASE"
}
dependencies {
implementation "org.springframework.boot:spring-boot-starter"
}
b/build.gradle:
plugins {
id "org.springframework.boot" version "1.5.17.RELEASE"
}
dependencies {
implementation "org.springframework.boot:spring-boot-starter"
}
c/build.gradle:
plugins {
id "org.springframework.boot" version "2.0.6.RELEASE"
}
dependencies {
implementation "org.springframework.boot:spring-boot-dependencies:2.0.6.RELEASE"
implementation "org.springframework.boot:spring-boot-starter"
}
App.java:
#SpringBootApplication
public class App implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
#Override
public void run(String... args) throws Exception {
System.out.println(SpringVersion.getVersion());
}
}
App.java is the same in all three subprojects. Executing ./gradlew clean :a:bootRun :b:bootRun :c:bootRun will output something like:
…
4.3.12.RELEASE
…
4.3.20.RELEASE
…
5.0.10.RELEASE
…
As you see, you're using three different Springs in three different subprojects.
EDIT
First of all, you can still use apply, just put them in subprojects.
Second, you can use plugins with your own repositories and dependencies, even with those not published in Gradle's Plugin Repository by adding a pluginManagement block in settings.gradle (this is Kotlin DSL from my project):
pluginManagement {
repositories {
gradlePluginPortal()
add(jcenter())
add(maven("http://my.jfrog.io"))
}
resolutionStrategy {
eachPlugin {
if (requested.id.id == "by.dev.madhead.some-plugin") {
useModule("by.dev.madhead:some-gradle-plugin:${requested.version}")
}
}
}
}
Now I am able to use by.dev.madhead.some-plugin in plugins DSL across the project:
plugins {
id("by.dev.madhead.some-plugin").version("42")
}
And it will be substituted by by.dev.madhead:some-gradle-plugin:42

spring web developement - disable caching for static content

I'm developping a angularjs application with Spring.
I often have to change my html/javascript file and I noticed that spring is caching static contents. How can I disable that?
I already tried this ...
#Configuration
#AutoConfigureAfter(DispatcherServletAutoConfiguration.class)
class WebMvcConfig extends WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter {
#Autowired
private Environment env;
#Bean
public ResourceUrlEncodingFilter resourceUrlEncodingFilter() {
return new ResourceUrlEncodingFilter();
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
boolean devMode = this.env.acceptsProfiles("dev");
//boolean useResourceCache = !devMode;
boolean useResourceCache = false;
Integer cachePeriod = devMode ? 0 : null;
registry.addResourceHandler("/public/**")
.addResourceLocations("/public/", "classpath:/public/")
.setCachePeriod(cachePeriod)
.resourceChain(useResourceCache)
.addResolver(new GzipResourceResolver())
.addResolver(new VersionResourceResolver().addContentVersionStrategy("/**"))
.addTransformer(new AppCacheManifestTransformer());
}
}
and that ...
WebContentInterceptor webContentInterceptor;
public #Bean WebContentInterceptor webContentInterceptor () {
if (this.webContentInterceptor == null) {
this.webContentInterceptor = new WebContentInterceptor();
this.webContentInterceptor.setAlwaysUseFullPath (true);
this.webContentInterceptor.setCacheSeconds (0);
this.webContentInterceptor.setCacheMappings (new Properties() {
private static final long serialVersionUID = 1L;
{
put ("/styles/**", "0");
put ("/scripts/**", "0");
put ("/images/**", "0");
put ("/js/**", "0");
}
});
}
return this.webContentInterceptor;
}
this is my build.gradle file
group 'xyz'
version '1.0-SNAPSHOT'
buildscript{
repositories{
mavenCentral()
}
dependencies{
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.3.2.RELEASE")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'spring-boot'
sourceCompatibility = 1.8
targetCompatibility = 1.8
repositories {
mavenCentral()
maven { url "https://repository.jboss.org/nexus/content/repositories/releases" }
}
dependencies {
compile 'org.springframework.boot:spring-boot-starter-web'
compile 'org.springframework.security:spring-security-web:4.0.3.RELEASE'
compile 'net.sf.dozer:dozer:5.4.0'
compile 'org.springframework.boot:spring-boot-starter-data-jpa'
compile 'com.h2database:h2'// For Testing purpose
compile 'com.google.guava:guava:19.0' // google library for data collections
testCompile("junit:junit")
//testCompile group: 'junit', name: 'junit', version: '4.11'
}
task wrapper(type: Wrapper){
gradleVersion = '2.3'
}
configurations.all {
// https://stackoverflow.com/questions/14024756/slf4j-class-path-contains-multiple-slf4j-bindings/25694764#25694764
exclude module: 'slf4j-log4j12'
}
Just put this configuration option into your application.properties:
spring.resources.chain.cache=false # Disable caching in the Resource chain.
You may want to also take a look at more fine grained config options related to Static content served by Spring Boot (scroll down to section # SPRING RESOURCES HANDLING).
Additionally, there may be static resources cached by infrastructure that is not handled by Spring Boot and it's container (e.g Web Browser). If you want to overcome this type of caching, there is option to use technique called cache busting. Read this section of Spring Boot docs to get more info about it.
It was a silly mistake. I was editing the HTML/CSS/JS source files but the compiled and deployed version was not affected from this modification.
To see not compiled but the very version of static content you're editing set in application.yml something like:
spring:
profiles: dev
resources:
static-locations: file:src/main/resources/static
But do so only in dev profile to avoid problem after deployment.
Add this is in application.properties
Use this if you want to cache for a particular amount of time
spring.resources.cache.cachecontrol.cache-public=true spring.resources.cache.cachecontrol.max-age=2000 #(2 seconds)
Use this if you don't want any cache
spring.resources.cache.cachecontrol.no-cache=true
But try to adopt first way, as it is not a good practice to load static content every time from server

Categories