Howto handle clash of tasks for two gradle plugins? - gradle

I use gradle with the two plugins com.jfrog.artifactory and io.swagger.core.v3.swagger-gradle-plugin .
Now I want to configure as described here https://github.com/swagger-api/swagger-core/tree/master/modules/swagger-gradle-plugin the generation of code. But it seems that the resolve task has already been defined from artifactory. How do I adress the method of swagger-plugin directly?
This is in my build.gradle:
resolve {
outputFileName = 'bananas'
outputFileName = 'PetStoreAPI'
outputFormat = 'JSON'
prettyPrint = 'TRUE'
classpath = sourceSets.main.runtimeClasspath
resourcePackages = ['io.test']
outputDir = file('test')
}
and this is the error message: Could not set unknown property 'outputFileName' for object of type org.jfrog.gradle.plugin.artifactory.dsl.ResolverConfig.

There is indeed a clash between Artifactory resolve extension and Swagger plugin resolve tasks (of type import io.swagger.v3.plugins.gradle.tasks.ResolveTask)
One way to solve this is to reference the swagger tasks explicitly using fully-qualified name, as follows:
io.swagger.v3.plugins.gradle.tasks.ResolveTask swaggerResolve = tasks.getByName("resolve")
swaggerResolve.configure {
outputFileName = 'PetStoreAPI'
outputFormat = 'JSON'
prettyPrint = 'TRUE'
classpath = sourceSets.main.runtimeClasspath
resourcePackages = ['io.test']
outputDir = file('test')
}
EDIT
Simpler solution , see Lukas's comment
tasks.resolve {
outputFileName = 'PetStoreAPI'
// ....
}

Related

Cannot import "org.jetbrains.exposed.sql.Database" in KTOR

I was recently working on a MySQL database and wanted to use the database as my data source in KTOR. To use the database, I decided to use the org.jetbrains.exposed.sql.Database
and javax.sql.DataSource imports. I'm working in IntelliJ.
My test code looks like this:
import org.jetbrains.exposed.sql.Database
import javax.sql.DataSource
fun main(args: Array<String>): Unit = io.ktor.server.netty.EngineMain.main(args)
val databaseUrl = "jdbc:mysql://localhost:3307/databaseName"
val username = "root"
val password = " "
// Create a DataSource object
val dataSource: DataSource = Database.connect(
url = databaseUrl,
driver = "com.mysql.jdbc.Driver",
user = username,
password = password
)
Somehow, I can't import the org.jetbrains.exposed.sql.Database , even though I added the dependency in my build.gradle.kts file:
dependencies {
implementation("com.mysql.jdbc:mysql-connector-java:8.0.22")
implementation("org.jetbrains.exposed:exposed:0.18.7")
implementation("io.ktor:ktor-server-core:$ktor_version")
implementation("io.ktor:ktor-server-netty:$ktor_version")
implementation("io.ktor:ktor-server-content-negotiation:$ktor_version")
implementation("io.ktor:ktor-serialization-kotlinx-json:$ktor_version")
implementation("ch.qos.logback:logback-classic:$logback_version")
testImplementation("io.ktor:ktor-server-test-host:$ktor_version")
testImplementation("org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version")
implementation(kotlin("stdlib-jdk8"))
}
I tried syncing the gradle file, rebuilding the project and cleaning the project. Am I missing something? Thanks!
Ok so I solved it by using a different dependency in my build.gradle file:
implementation("org.jetbrains.exposed:exposed-core:0.41.1")
Instead of:
implementation("org.jetbrains.exposed:exposed:0.18.7")

Gradle how to use custom buildFile with projectBuilder

I am trying to pass a custom buildFile to ProjectBuilder:
given:
File tempDir = File.createTempDir()
File buildFile = new File(tempDir,'build.gradle')
buildFile << """
plugins {
id 'com.myplugin.gradle'
}
"""
when:
Project project = new ProjectBuilder()
.builder()
.withProjectDir(tempDir)
.build()
then:
project.getProjectDir() == tempDir
project.tasks.getByName("oneOfMyTasks") != null
However, that buildFile is not getting applied.
When I apply it directly, it does work:
when:
def project = new ProjectBuilder().build()
project.plugins.apply('com.myplugin.gradle')
then:
project.tasks.getByName("oneOfMyTasks") != null
How do I provide a custom buildFile to ProjectBuilder?
The ProjectBuilder implementation doesn't need a build script file. Instead you have to apply plugin directly to the Project instance returned by the build() method.

flyway + gradle + spring boot configuration

How can I configure flyway in build.gradle to get url ,username, password from other properties file?
Instead of this:
flyway {
url = 'jdbc:postgresql://localhost:5432/db'
user = 'a'
password = 'a'
locations = ['filesystem:db/migration']
}
something like this:
flyway {
path = ['filesystem:src/main/resources/data-access.properties']
locations = ['filesystem:db/migration']
}
You can do something like this:
ext.flywayProps = new Properties()
flywayProps.load(new FileInputStream(this.projectDir.absolutePath + "/src/main/resources/data-access.properties"))
In the root of your build script, it will load a properties file into local variable of Properties type. After that you can use this properties the way you need it, like so for example:
flyway {
url = 'jdbc:postgresql://flywayProps['dbIp']:flywayProps['dbPort']/db'
user = flywayProps['dbUsername']
password = flywayProps['dbPassword']
locations = ['filesystem:db/migration']
}
And in your data-access.properties you need to specify it as follows:
dbIp=localhost
dbPort=5432
dbUsername=a
dbPassword=a

How to use imgscalr using Grails

I've just begun using Groovy and Grails the last few days. I don't have any prior experience of Java, so you'll have to excuse this (probably) very basic question. I've searched Google and Stack Overflow and haven't found anything that helps me with the actually installation.
I have got an image upload working, and I am storing the file on the server. I used a IBM Grails tutorial to guide me through it. That works fine.
I would also like to resize the file in a large, medium, and small format. I wanted to use imgscalr for this, but I cant get it to work. I have downloaded version 4.2 which contains various .jar files. Do I need to put these somewhere on the server and reference them? The only thing I've done is add these lines to buildConfig.groovy
dependencies {
// specify dependencies here under either 'build', 'compile', 'runtime', 'test' or 'provided' scopes eg.
// runtime 'mysql:mysql-connector-java:5.1.20'
compile 'org.imgscalr:imgscalr-lib:4.2'
}
and import org.imgscalr.Scalr.* in my PhotoController.Groovy
Here's my code for saving the file onto the server, I would also like to resize and save the image.
def save() {
def photoInstance = new Photo(params)
// Handle uploaded file
def uploadedFile = request.getFile('photoFile')
if(!uploadedFile.empty) {
println "Class: ${uploadedFile.class}"
println "Name: ${uploadedFile.name}"
println "OriginalFileName: ${uploadedFile.originalFilename}"
println "Size: ${uploadedFile.size}"
println "ContentType: ${uploadedFile.contentType}"
def webRootDir = servletContext.getRealPath("/")
def originalPhotoDir = new File(webRootDir, "/images/photographs/original")
originalPhotoDir.mkdirs()
uploadedFile.transferTo(new File(originalPhotoDir, uploadedFile.originalFilename))
BufferedImage largeImg = Scalr.resize(uploadedFile, 1366);
def largePhotoDir = new File(webRootDir, "/images/photographs/large")
largePhotoDir.mkdirs()
photoInstance.photoFile = uploadedFile.originalFilename
}
if (!photoInstance.hasErrors() && photoInstance.save()) {
flash.message = "Photo ${photoInstance.id} created"
redirect(action:"list")
}
else {
render(view:"create", model:[photoInstance: photoInstance])
}
}
The error I'm getting is No such property: Scalr for class: garethlewisweb.PhotoController
I'm obviously doing something very wrong. Any guidance appreciated.
This is the first google result for "How to use imgscalr in grails" and I was surprised with the lack of informations and examples when googling it. Although the first answer is close, there's still a few mistakes to be corrected.
To anyone that ended here like me through google, heres a more detailed example of how to correctly use this nice plugin:
First, declare the plugin in your BuildConfig.groovy file:
dependencies {
// specify dependencies here under either 'build', 'compile', 'runtime', 'test' or 'provided' scopes eg.
// runtime 'mysql:mysql-connector-java:5.1.20'
compile 'org.imgscalr:imgscalr-lib:4.2'
}
Then, after installed, just paste this piece of code in your controller, in the action that receives the multi-part form with the image uploaded.
def create() {
def userInstance = new User(params)
//saving image
def imgFile = request.getFile('myFile')
def webRootDir = servletContext.getRealPath("/")
userInstance.storeImageInFileSystem(imgFile, webRootDir)
(...)
}
Inside my domain, I implemented this storeImageInFileSystem method, that will resize the image and store it in the filesystem. But first, import this to the file:
import org.imgscalr.Scalr
import java.awt.image.BufferedImage
import javax.imageio.ImageIO
And then, implement the method:
def storeImageInFileSystem(imgFile, webRootDir){
if (!imgFile.empty)
{
def defaultPath = "/images/userImages"
def systemDir = new File(webRootDir, defaultPath)
if (!systemDir.exists()) {
systemDir.mkdirs()
}
def imgFileDir = new File( systemDir, imgFile.originalFilename)
imgFile.transferTo( imgFileDir )
def imageIn = ImageIO.read(imgFileDir);
BufferedImage scaledImage = Scalr.resize(imageIn, 200); //200 is the size of the image
ImageIO.write(scaledImage, "jpg", new File( systemDir, imgFile.originalFilename )); //write image in filesystem
(...)
}
}
This worked well for me. Change any details as the need, like the system diretory or the size of the image.
Instead of
import org.imgscalr.Scalr.*
You want
import org.imgscalr.Scalr
import javax.imageio.ImageIO
Then resize needs a BufferedImage (looking at the JavaDocs), so try:
def originalPhotoDir = new File(webRootDir, "/images/photographs/original")
originalPhotoDir.mkdirs()
def originalPhotoFile = new File(originalPhotoDir, uploadedFile.originalFilename)
uploadedFile.transferTo( originalPhotoFile )
// Load the image
BufferedImage originalImage = ImageIO.read( originalPhotoFile )
// Scale it
BufferedImage largeImg = Scalr.resize(uploadedFile, 1366);
// Make the destination folder
def largePhotoDir = new File(webRootDir, "/images/photographs/large" )
largePhotoDir.mkdirs()
// Write the large image out
ImageIO.write( largeImg, 'png', new File( largePhotoDir, uploadedFile.originalFilename )
Of course, you'll have to watch for files overwriting already existing images
Put the jar file(s) in the 'lib' directory of your Grails application. You may then delete that line from BuildConfig.groovy

Difference between (guava) Resources.getResource("bddconf.xml") and properties.getClass().getResourceAsStream("bddconf.xml");

In a maven war project, i use jetty-maven-plugin as developpement container.
i filtered some resources files, and in particular let's name it "bddconf.xml".
This file is filtered by maven and put in target/classes directory.
An old home-made bdd fwk search after this file with this snippet :
Properties properties = new Properties();
InputStream inputstream = properties.getClass().getResourceAsStream("/bddconf.xml");
When i run this snippet, in my webapp (in jetty), inputStream is null.
Whereas with this snippet, in the same method :
import com.google.common.io.Resources;
String file = Resources.getResource("bddconf.xml").getFile();
File file2 = new File(file);
logger.info("Does bdd file exists : [" + file2.exists() + "] file : [" + file2.toString() + "]");
// Does bdd file exists : [true] file : [..path..\target\classes\bbdconf.xml]
It works, so what's the difference between this two methods ?
May be Properties class and guava Resources class have different ClassLoaders (with different privileges), because Class.getResource() and Resources.getResource() do the same job for you. You can look at the sources of guava:
public static URL getResource(String resourceName) {
URL url = Resources.class.getClassLoader().getResource(resourceName);
checkArgument(url != null, "resource %s not found.", resourceName);
return url;
}
Class.getResource:
name = resolveName(name);
ClassLoader cl = getClassLoader0();
if (cl==null) {
// A system class.
return ClassLoader.getSystemResource(name);
}
return cl.getResource(name);

Resources