Gradle how to use custom buildFile with projectBuilder - gradle

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.

Related

Howto handle clash of tasks for two gradle plugins?

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'
// ....
}

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

Maven module dependency and resources

I have a maven Project say ProjectA, and there is a class say ClassA in this project which uses the files from resource folder, I am using following way to read from resource:
String fileName = IPToGeoMapper.class.getResource("/resourceFile.txt").getFile();
File resourceFile = new File(fileName);
and it works like charm.
Now, when I create artifact out of this project (I have tried extracting the created jar and it has resourceFile.txt packed in the jar), and use that as a dependency in other project say ProjectB, ClassA no more finds the resourceFile.txt as it tries to browse though resources folder of ProjectB.
I want the best global solution which will work in all the projects where I import artifact created from ProjectA
What is the best way to handle this?
Try this way , I am taking an example of reading a property file.
Properties propfile = new Properties();
propfile.load(PropertyUtils.class.getClassLoader()
.getResourceAsStream(
"applicationprops.properties"));
BufferedReader reader = new BufferedReader(new InputStreamReader(ClassA.class.getClassLoader().getResourceAsStream("file.txt")));
StringBuilder out = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
out.append(line);
}
System.out.println(out.toString()); //Prints the string content read from input stream
reader.close();

Save changes to Property File in Grails

I have a grails application that reads from a property file. I created an administration page, that allows the user to view the settings in this file. I want to allow the user to update the various properties and save them back to the property file using Grails.
My problem is I cant seem to figure out how to save the changes back to the property file.
Here is my code that reads from the file and makes changes to the properties:
def env = params.getAt("environment");
if (env != null){
//Read from Property file based on user selection
def props = new Properties()
def cl = Thread.currentThread().contextClassLoader
def filepath = env+'.properties'
props.load servletContext.getResourceAsStream("/WEB-INF/"+ filepath)
Enumeration e = props.propertyNames();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
def input = params.getAt(key)
if (input != null){
props.setProperty(key,input)
}
}
//props.store(propFile.newWriter(), null)
}
Any Ideas on how to save/overwrite the example.properties file in /WEB-INF/example.properties?
I think that you might be looking for the getRealPath method in ServletContext
http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContext.html#getRealPath(java.lang.String)
Simple example that shows you how to use it
http://82.157.70.109/mirrorbooks/javaservletjspcookbook/0596005725_jsvltjspckbk-chp-14-sect-7.html

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

Resources