Failing scripts in groovy using Grab - groovy

The following groovy scripts fail using command line
#Grab("org.apache.poi:poi:3.9")
println "test"
Error:
unexpected token: println # line 2, column 1.
println "test"
^
1 error
Removing the Grab, it works!
Anything I missed?
$>groovy -v
Groovy Version: 2.1.7 JVM: 1.7.0_25 Vendor: Oracle Corporation OS: Linux

Annotations can only be applied to certain targets. See SO: Why can't I do a method call after a #Grab declaration in a Groovy script?
#Grab("org.apache.poi:poi:3.9")
dummy = null
println "test"
Alternatively you can use grab as a method call:
import static groovy.grape.Grape.grab
grab(group: "org.apache.poi", module: "poi", version: "3.9")
println "test"
For more information refer to Groovy Language Documentation > Dependency management with Grape.

File 'Grabber.groovy'
package org.taste
import groovy.grape.Grape
//List<List[]> artifacts => [[<group>,<module>,<version>,[<Maven-URL>]],..]
static def grab (List<List[]> artifacts) {
ClassLoader classLoader = new groovy.lang.GroovyClassLoader()
def eal = Grape.getEnableAutoDownload()
artifacts.each { artifact -> {
Map param = [
classLoader: classLoader,
group : artifact.get(0),
module : artifact.get(1),
version : artifact.get(2),
classifier : (artifact.size() < 4) ? null : artifact.get(3)
]
println param
Grape.grab(param)
}
}
Grape.setEnableAutoDownload(eal)
}
Usage :
package org.taste
import org.taste.Grabber
Grabber.grab([
[ "org.codehaus.groovy.modules.http-builder", "http-builder", '0.7.1'],
[ "org.postgresql", "postgresql", '42.3.1', null ],
[ "com.oracle.database.jdbc", "ojdbc8", '12.2.0.1', null]
])

Related

Gradle - cannot instantiate ivy class

What am I doing wrong here? The ultimate goal is to download *.properties from the URL.
[ I know resolver is not needed, was just trying out to see if there was a class name issue. ]
Error:
build file '/home/awm/t/build.gradle': 13: unable to resolve class org.apache.ivy.plugins.resolver.URLResolver
# line 13, column 20.
def resolver = new org.apache.ivy.plugins.resolver.URLResolver()
^
build file '/home/awm/t/build.gradle': 14: unable to resolve class org.apache.ivy.util.url.ApacheURLLister
# line 14, column 21.
def urlLister = new org.apache.ivy.util.url.ApacheURLLister()
^
Code:
plugins {
id "de.undercouch.download" version "2.0.0"
}
import de.undercouch.gradle.tasks.download.Download
import org.apache.ivy.util.url.*
task downloadDirectory {
def dir = 'http://127.0.0.1:8081/artifactory/gradle-local/props/'
def resolver = new org.apache.ivy.plugins.resolver.URLResolver()
def urlLister = new org.apache.ivy.util.url.ApacheURLLister()
def files = urlLister.listFiles(new URL(dir))
download {
src files
dest "lib"
}
}
defaultTasks 'downloadDirectory'
From Gradle 2.0 on you need to include a build script dependency to Apache Ivy in order to make this recipe work. Put the following right at the beginning of your build script.
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'org.apache.ivy:ivy:2.3.0'
}
}
example: https://github.com/michel-kraemer/gradle-download-task/blob/ddb384d3ee86f038c61ec4e77f21b814b1557a1a/examples/directory.gradle
another use-cases of download task: https://www.michel-kraemer.com/recipes-for-gradle-download/

Unusually low test coverage reported when using Cobertura with Gradle and Groovy code

I'm developing a Gradle plugin and I'm trying to configure my project to let me get code coverage metrics on it. I have unit and integration tests based on the Spock framework.
I've tried using both Jacoco and Cobertura to analyse my project. Here is the configuration I'm working with:
Gradle: 2.2.1
Groovy: 2.3.6
Ant: Apache Ant(TM) version 1.9.3 compiled on December 23 2013
JVM: 1.8.0_25 (Oracle Corporation 25.25-b02)
OS: Mac OS X 10.10.1 x86_64
I'm using the gradle-cobertura-plugin v2.2.5.
Cobertura
In the case of Cobertura, my project's reported line coverage is only 35%. There are large sections of code that I have written tests for that are reported as not tested by Cobertura:
In particular, Cobertura reports no coverage for the nested static class Version.Parser despite there being a complete Spock specification devoted to this:
package com.github.tagc.semver
import spock.lang.Specification
import spock.lang.Unroll
import com.github.tagc.semver.Version.Parser
#Unroll
class VersionParserSpec extends Specification {
private static final Parser PARSER = Version.Parser.getInstance()
def "Version information should be extracted from files if parsing is not strict"() {
given:
def versionFileText = "version='$versionString'"
expect:
PARSER.parse(versionFileText, false) == version
where:
versionString | version
'0.1.2-SNAPSHOT' | new Version(0,1,2,false)
'1.2.4' | new Version(1,2,4,true)
'1.3-SNAPSHOT' | new Version(1,3,0,false)
'0.4' | new Version(0,4,0,true)
}
def "Valid version representation should be parsed successfully"() {
expect:
PARSER.parse(input, true) == version
where:
input | version
'0.1' | new Version(0,1,0,true)
'1.3-SNAPSHOT' | new Version(1,3,0,false)
'1.1.1' | new Version(1,1,1,true)
'0.2.7' | new Version(0,2,7,true)
'0.4.9-SNAPSHOT' | new Version(0,4,9,false)
'6.3.16-SNAPSHOT' | new Version(6,3,16,false)
' 1.2.3-SNAPSHOT' | new Version(1,2,3,false)
' 1.3.5-SNAPSHOT ' | new Version(1,3,5,false)
}
def "Invalid version representation (#input) should cause an exception to be thrown"() {
when:
PARSER.parse(input, true)
then:
thrown(IllegalArgumentException)
where:
input << [
'1.2.a',
'1,2,3',
'2.4.-1',
'3-4-9',
'1.4.5-SNPSHOT',
'1.4.5-SNAPSHOTasd'
]
}
}
Below are the relevant parts of my Gradle build script:
buildscript {
repositories { jcenter() }
dependencies {
// Cobertura plugin
classpath "net.saliman:gradle-cobertura-plugin:2.2.5"
}
}
configurations.all {
resolutionStrategy {
force 'org.ow2.asm:asm:5.0.3'
forcedModules = [ 'org.ow2.asm:asm:5.0.3' ]
}
}
apply plugin: 'net.saliman.cobertura'
check.dependsOn 'cobertura'
cobertura {
coverageFormats = [ 'html', 'xml' ]
}
Jacoco
In comparison, Jacoco reports a much more plausible coverage of 68% (by instructions).
Coverage of the same Version.Parser section is reported as this:
The relevant parts of my build script are:
apply plugin: "jacoco"
task integrationTest(type: Test) {
description = 'Runs the integration tests.'
group = 'verification'
testClassesDir = sourceSets.integrationTest.output.classesDir
classpath = sourceSets.integrationTest.runtimeClasspath
jacoco {
destinationFile = file("$buildDir/jacoco/integrationTest.exec")
classDumpFile = file("$buildDir/classes/integrationTest")
}
}
jacocoTestReport {
executionData test, integrationTest
reports {
xml.enabled true
html.enabled true
}
}
Since Jacoco seems to be working fine, I'd ideally like to just stick with it. However, Sonar doesn't seem to work properly with Jacoco when writing code in Groovy, so I seem to be stuck with Cobertura. Is there any reason why Cobertura could be giving me these coverage results?
EDIT
I have raised this as an issue on the Gradle Cobertura plugin Github repository.
I haven't tested it myself but apparently this issue is fixed as of v2.2.7 of the Gradle plugin, which uses v2.1.1 of Cobertura (source).

changing startup MVC group in Application.groovy issue

I've created new Groffin module using IntelliJ. I was prompted for create-app command.
Creating a module was fine, and as you know, by default, when you ran an app, it shows applet with default content "Content goes here".
Next, I've added a second login MVC group in Application.groovy:
application {
title = 'Soms'
startupGroups = ['login']
// Should Griffon exit when no Griffon created frames are showing?
autoShutdown = true
// If you want some non-standard application class, apply it here
//frameClass = 'javax.swing.JFrame'
}
mvcGroups {
// MVC Group for "soms"
'soms' {
model = 'soms.SomsModel'
view = 'soms.SomsView'
controller = 'soms.SomsController'
}
// MVC Group for "login"
'login' {
model = 'soms.LoginModel'
view = 'soms.LoginView'
controller = 'soms.LoginController'
}
}
I've also created:
LoginModel.groovy (groovy class)
LoginController.groovy (groovy class)
LoginView.groovy (groovy script)
in the corresponding folders.
When I run project, it's giving errors:
Base Directory: D:\work\griffon\soms Running script
C:\Griffon-1.2.0\scripts\RunApp.groovy Resolving dependencies...
Dependencies resolved in 633ms. Environment set to development
Resolving framework plugin dependencies ... Framework plugin
dependencies resolved in 1114 ms. Resolving plugin dependencies ...
Plugin dependencies resolved in 741 ms. [griffonc] Compiling 1 source
file to d:\Users\akarasaev.griffon\1.2.0\projects\soms\classes\main
Launching application ... 2013-04-15 10:26:44,788 [main] INFO
griffon.swing.SwingApplication - Initializing all startup groups:
[login] 2013-04-15 10:26:46,311 [AWT-EventQueue-0] ERROR
org.codehaus.griffon.runtime.builder.UberBuilder - An error occurred
while building soms.LoginView#34a083f2
groovy.lang.MissingPropertyException: No such property: CENTER for
class: org.codehaus.griffon.runtime.builder.UberBuilder at
org.codehaus.griffon.runtime.builder.UberBuilder.getProperty(UberBuilder.groovy:187)
at
org.codehaus.griffon.runtime.builder.UberInterceptorMetaClass.getProperty(UberInterceptorMetaClass.groovy:210)
at soms.LoginView.run(LoginView.groovy:18) at
org.codehaus.griffon.runtime.builder.UberInterceptorMetaClass.invokeMethod(UberInterceptorMetaClass.groovy:152)
at
org.codehaus.griffon.runtime.builder.UberBuilder.build(UberBuilder.groovy:160)
at
org.codehaus.griffon.runtime.core.AbstractMVCGroup$1.run(AbstractMVCGroup.java:129)
2013-04-15 10:26:46,324 [main] ERROR
griffon.util.GriffonExceptionHandler - Uncaught Exception
groovy.lang.MissingPropertyException: No such property: CENTER for
class: org.codehaus.griffon.runtime.builder.UberBuilder at
org.codehaus.griffon.runtime.builder.UberBuilder.getProperty(UberBuilder.groovy:187)
at
org.codehaus.griffon.runtime.builder.UberInterceptorMetaClass.getProperty(UberInterceptorMetaClass.groovy:210)
at soms.LoginView.run(LoginView.groovy:18) at
org.codehaus.griffon.runtime.builder.UberInterceptorMetaClass.invokeMethod(UberInterceptorMetaClass.groovy:152)
at
org.codehaus.griffon.runtime.builder.UberBuilder.build(UberBuilder.groovy:160)
at
org.codehaus.griffon.runtime.core.AbstractMVCGroup$1.run(AbstractMVCGroup.java:129)
The same error happens when I try to run from command prompt.
Environment:
Win 7 Pro, 64-bit
IntelliJ IDEA ver 12.1
Griffon-1.2.0 JDK 1.6
LoginModel.groovy:
package soms
import groovy.beans.Bindable
import griffon.transform.PropertyListener
import static griffon.util.GriffonNameUtils.isBlank
#Bindable
#PropertyListener(enabler)
class LoginModel {
String login
String password
boolean submitEnabled
boolean resetEnabled
private enabler = { e ->
submitEnabled = !isBlank(login) && !isBlank(password)
resetEnabled = !isBlank(login) || !isBlank(password)
}
}
LoginView.groovy:
package soms
application(title: 'Login',
preferredSize: [320, 240],
pack: true,
locationByPlatform: true
)
borderLayout()
panel(constraints: CENTER, border: emptyBorder(6)) {
gridLayout(rows:3, columns:2, hgap:6, vgap:6)
label: 'login:'
textField columns: 20, text: bind(target: model, 'login', mutual: true)
label: 'password:'
textField columns: 20, text: bind(target: model, 'password', mutual: true)
}
panel(constraints: SOUTH){
gridLayout(rows:1, cols:2, hgap:6, vgap:6 )
button('reset', actionPerformed: controller.reset, enabled: bind{model.resetEnabled})
button('submit', actionPerformed: controller.reset, enabled: bind{model.submitEnabled})
}
LoginController.groovy:
package soms
class LoginController {
def model
def view
}
I found out that my LoginController.groovy was incomplete.
Now it's working and the correct LoginController.groovy as follows:
package soms
import griffon.transform.Threading
class LoginController {
def model
def view
#Threading(Threading.Policy.SKIP)
def reset = {
model.login = ''
model.password = ''
}
def submit = {
println "Login: ${model.login}"
println "Password: ${model.password}"
}
}

How to run cucumber-jvm tests using Gradle

I am trying to get a project going using the new Cucumber-jvm system and Gradle as my build system.
I have used the example Java code in the GitHub cucumber-jvm project(https://github.com/cucumber/cucumber-jvm).
My project is set up in IntelliJ and the IDE is able to run the test.
However, Gradle does not find any tests to run. I know this because I broke the test and Gradle said nothing. It also said nothing when it was working.
The class it is trying to run looks like this:
import cucumber.junit.Cucumber;
import cucumber.junit.Feature;
import org.junit.runner.RunWith;
#RunWith(Cucumber.class)
#Feature(value = "CarMaintenance.feature")
public class FuelCarTest {
}
I'm new to both cucumber and Gradle!!
I remember having trouble with Gradle and Cucumber with the junit runner.
I eventually gave up and created a gradle task using the command line runner.
task executeFeatures(type: JavaExec, dependsOn: testClasses) {
main = "cucumber.cli.Main"
classpath += files(sourceSets.test.runtimeClasspath, file(webAppDir.path + '/WEB-INF/classes'))
args += [ '-f', 'html:build/reports/cucumber', '-g', 'uk.co.filmtrader', 'src/test/resources/features']
}
-f Folder for html report output
-g Package name for glue/step code
src/test/resources/features Where the feature files are
With the following dependencies
testCompile 'org.mockito:mockito-all:1.9.5',
'junit:junit:4.11',
'org.hamcrest:hamcrest-library:1.3',
'info.cukes:cucumber-java:1.0.14',
'info.cukes:cucumber-junit:1.0.14',
'info.cukes:cucumber-spring:1.0.14'
Update for version 4.2.5
There had been some minor changes over time:
the package name of the cli changed to cucumber.api.cli.Main
The flag -f seems no longer to be working and causes an error
So I ended up with the following task definition in my build.gradle:
task executeFeatures(type: JavaExec, dependsOn: testClasses) {
main = "cucumber.api.cli.Main"
classpath += files(sourceSets.test.runtimeClasspath)
args += [ '-g', 'uk.co.filmtrader', 'src/test/resources/features']
}
other way can be to create a task and include runner class for test
build.gradle-
task RunCukesTest(type: Test) << {
include "RunCukesTest.class"
}
testCompile 'io.cucumber:cucumber-java:4.2.0'
testCompile 'io.cucumber:cucumber-junit:4.2.0'
your class -
#RunWith(Cucumber.class)
#CucumberOptions(dryRun = false, strict = true, features = "src/test/resources", glue
= "com.gradle.featuretests",monochrome = true)
public class RunCukesTest {
}
simply hit the command :- gradle RunCukesTest
Considering:
Your .feature files are in src/test/resources/cucumber/features and
your glue classes are in com.example.myapp.glue
Then, following what is explained in the docs, you can do in build.gradle:
dependencies {
// ...
testImplementation("io.cucumber:cucumber-java:6.2.2")
testImplementation("io.cucumber:cucumber-junit:6.2.2")
testImplementation("io.cucumber:cucumber-junit-platform-engine:6.2.2")
}
configurations {
cucumberRuntime {
extendsFrom testImplementation
}
}
// this enables the task `gradle cucumber`
task cucumber() {
dependsOn assemble, compileTestKotlin
doLast {
javaexec {
main = "io.cucumber.core.cli.Main"
classpath = configurations.cucumberRuntime + sourceSets.main.output + sourceSets.test.output
args = ['--strict', '--plugin', 'pretty', '--plugin', 'junit:build/test-results/cucumber.xml', '--glue', 'com.example.myapp.glue', 'src/test/resources/cucumber/features']
}
}
}
// (OPTIONAL) this makes `gradle test` also include cucumber tests
tasks.test {
finalizedBy cucumber
}
Now gradle cucumber will run the cucumber tests.
If you added the last part, gradle test will also run cucumber tests.
The args part supports what goes in the #CucumberOptions annotation of the runner. More details: https://cucumber.io/docs/cucumber/api/#list-configuration-options

ElasticSearch 1.5 upgrade: JodaTime conversion script error

I'm working through upgrading our ElasticSearch version from 1.3 to 1.5. We use the Java API heavily. the following script in an ES query:
{
"script" : {
"script" : "values contains (int)doc['timestamp'].date.toDateTime(DateTimeZone.forID('America/New_York')).getMonthOfYear()",
"params" : {
"values" : [ 1 ]
},
"lang" : "groovy"
}
}
This works with 1.3, but gives the following error in 1.5:
org.elasticsearch.action.search.SearchPhaseExecutionException: Failed to execute phase [query_fetch], all shards failed; shardFailures {[XwOu9zq0TMi2uOptdfIS7w][eventdata][0]: QueryPhaseExecutionException[[eventdata][0]: query[filtered(ConstantScore(ScriptFilter(values contains (int)doc['timestamp'].date.toDateTime(DateTimeZone.forID('America/New_York')).getMonthOfYear().toString())))->cache(org.elasticsearch.index.search.nested.NonNestedDocsFilter#2a8c0465)],from[0],size[10]: Query Failed [Failed to execute main query]]; nested: GroovyScriptExecutionException[MissingMethodException[No signature of method: Script1.contains() is applicable for argument types: (java.lang.Class) values: [int]
Possible solutions: toString(), toString(), notify()]]; }
at org.elasticsearch.action.search.type.TransportSearchTypeAction$BaseAsyncAction.onFirstPhaseResult(TransportSearchTypeAction.java:238)
at org.elasticsearch.action.search.type.TransportSearchTypeAction$BaseAsyncAction$1.onFailure(TransportSearchTypeAction.java:184)
at org.elasticsearch.search.action.SearchServiceTransportAction$23.run(SearchServiceTransportAction.java:565)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
What's the best way to address this?
That looks like a brackets issue with the cast, so it thinks you're passing int to contains. Try adding brackets to help out the parser:
values.contains((int)doc['timestamp'].date.toDateTime(DateTimeZone.forID('Ameri‌​ca/New_York')).getMonthOfYear())

Resources