How add dependencies into groovy script? - groovy

I try to add HttpBuilder into groovy script, but can do it only manually (Alt+Ctrl+Shift+S add dependencie). But when I start script I have error in line of creating new httpbuilder instance java.lang.ClassNotFoundException: org.apache.http.client.HttpClient. I manualy add HttpClient, butClassNotFoundException: net.sf.json.JSONObject and so on. But when I add Ini library it works fine.
I also tried to use #Grab
main()
def main() {
#Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.7' )
def http = new groovyx.net.http.HTTPBuilder('http://www.codehaus.org')
And have compilation error
Error:Groovyc: While compiling GroovyTests: java.lang.RuntimeException: Error grabbing Grapes -- [download failed: net.sf.json-lib#json-lib;2.3!json-lib.jar]
And net in def http = new groovyx.net.http.HTTPBuilder('http://www.codehaus.org') is red and Cannot resolve a symbol 'net' error
will be glad to any help

Since you have now installed the groovy executables as per the comments, the following code:
#Grab('org.codehaus.groovy.modules.http-builder:http-builder:0.7')
import groovyx.net.http.HTTPBuilder
def http = new HTTPBuilder('https://jsonplaceholder.typicode.com')
def res = http.get(path: '/users')
println "Number of users: ${res.size()}"
should now run and print:
─➤ groovy solution.groovy
Number of users: 10
─➤
(tested on Groovy Version: 2.5.8 JVM: 1.8.0_232 Vendor: AdoptOpenJDK OS: Linux)
One thing that might be disrupting the artifact resolution is if you have a custom grapeConfig.xml file. This file (if it exists) should be under <user home dir>/.groovy/grapeConfig.xml and the default text that groovy uses if no grapeConfig.xml file is present can be found here:
https://github.com/apache/groovy/blob/master/src/resources/groovy/grape/defaultGrapeConfig.xml
In addition, if you need to debug grapes downloads, you should try the following flags (again as mentioned in the comments):
─➤ groovy -Dgroovy.grape.report.downloads=true -Divy.message.logger.level=4 yourGroovyScript.groovy
which should print information on what grapes are actually doing when the resolution fails.
What does your groovy -v look like? i.e. what version of groovy and what jdk are you on?

Related

Using classpath when debugging groovy scripts

I'm new to Java and Groovy, and this is a really simple question on how to use classpath when debugging groovy scripts.
I setup my Groovy project according to https://gist.github.com/tknerr/42258e761f2a0f95a92b:
$ find src
src
src/main
src/main/groovy
src/main/groovy/impl
src/main/groovy/impl/FooImpl.groovy
src/test
src/test/groovy
src/test/groovy/main.groovy
$ head src/main/groovy/impl/FooImpl.groovy src/test/groovy/main.groovy
==> src/main/groovy/impl/FooImpl.groovy <==
package impl
class FooImpl {
def foo() {
"hello?!"
}
}
==> src/test/groovy/main.groovy <==
println new impl.FooImpl().foo()
And I have already build everything:
$ find build/classes
build/classes
build/classes/groovy
build/classes/groovy/main
build/classes/groovy/main/impl
build/classes/groovy/main/impl/FooImpl.class
build/classes/groovy/test
build/classes/groovy/test/main.class
My goal is to use existing classes in classpath without packaging them into .jar file each time when debugging my groovy scripts, but am wondering why I'm getting the following errors:
cd src/test/groovy
$ ls ../../../build/classes/
groovy
$ groovy --classpath ../../../build/classes/ main.groovy
.../src/test/groovy/main.groovy: 1: unable to resolve class impl.FooImpl
# line 1, column 9.
println new impl.FooImpl().foo()
^
1 error
Same with groovysh.
How can I make it working?

What should CLASSPATH be set to in order to use NekoHTML in Groovy?

I have found several snippets that use NekoHTML library in Groovy scripts, e.g.
def page = new XmlSlurper(new org.cyberneko.html.parsers.SAXParser()).parse('http://groovy.codehaus.org/')
def data = page.depthFirst().grep{ it.name() == 'A' && it.#href.toString().endsWith('.html') }.'#href'
data.each { println it }
So I downloaded Groovy, and then I downloaded NekoHTML.
NekoHTML is located here:
D:\TOOLS\nekohtml-1.9.18\
When I run the snippet, I get:
D:\SCRIPTS\webtesting.groovy: 4: unable to resolve class org.cyberneko.html.parsers.SAXParser
# line 4, column 27.
def page = new XmlSlurper(new org.cyberneko.html.parsers.SAXParser()).parse('http://groovy.codehaus.or
g/')
My research tells me that I need to include NekoHTML in the classpath.
So I set up an environment variable CLASSPATH and it equals:
CLASSPATH=D:\TOOLS\nekohtml-1.9.18\src
I opened another cmd window and ran my test groovy script. I get the same error as above.
What should my CLASSPATH be set to refer to NekoHTML components with org.cyberneko.html.parsers.SAXParser?
You will need nekohtml-1.9.18.jar and xercesImpl-2.10.0.jar on your classpath.
Or you could just add a #Grab to the top of your script
#Grab( 'net.sourceforge.nekohtml:nekohtml:1.9.18' )
And groovy webtesting.groovy would fetch these dependencies for you. Of course, it depends how the script is being run

Using groovy-wslite in SoapUI

I'm using SoapUI version 4.5.1 on a Windows 7 box to create a mock webservice. It includes a Groovy script that is fired at an OnRequest event which attempts to create and send a second response.
The issue is to do with the installation of the groovy-wslite library, which I'm trying to use in order to instantiate a SoapClient object which sends the additional response.
If I include the following at the top of the script (as per the wslite github site at https://github.com/jwagenleitner/groovy-wslite):
#Grab(group='com.github.groovy-wslite', module='groovy-wslite', version='0.7.1')
... I get the following error:
java.lang.NoClassDefFoundError: org/apache/ivy/core/settings/IvySettings
If I remove it from the script, I get the following error:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed: Script6.groovy: 23: unable to resolve class SOAPClient # line 23, column 18.
def client = new SOAPClient(clientURL)
^
org.codehaus.groovy.syntax.SyntaxException: unable to resolve class SOAPClient # line 23, column 18.
Can anyone suggest what I'm doing wrong, please? Do I need to install groovy-wslite separately within SoapUI?
Thanks in advance for any advice.
I have downloaded the groovy-wslite jar and added it to my SoapUI installation's bin/ext directory.

cucumber jvm CucumberException: No features found at []

In my cucumber -jvm, Maven, junit Setup I have my testRunner file as
package com.lebara.testrunner;
import cucumber.junit.Cucumber;
import org.junit.runner.RunWith;
#RunWith(Cucumber.class)
#Cucumber.Options(
glue = {"com.lebara.stepdefs","com.lebara.framework.main", "com.lebara.testrunner"},
features = "C:/Users/sarthak.dayanand/Documents/WebRefreshTest/CukeAutomation/LebaraWebAutomationTest1/src/main/resources",
format = {"pretty", "html:target/cucumber-html-report", "json-pretty:target/cucumber-report.json"},
tags = {"#UserJourney"}
)
public class RunCukesTest {
}
I have my feature file in the above mentioned directory.
If I run it, I get the following exception:
cucumber.runtime.CucumberException: No features found at [C:/Users/sarthak.dayanand/Documents/WebRefreshTest/CukeAutomation/LebaraWebAutomationTest1/src/main/resources/cucumber]...
If I remove the "features" option in the testrunner, it tries to look for feature files in the same directory as my testrunner.java
cucumber.runtime.CucumberException: No features found at [com/lebara/testrunner]
And if I put the feature files there, it works.
My question is why is my feature file not being picked up from my previous location, which I thought to be the default file structure for cucumber - maven setup.
How do I make it pick up from there? Help appreciated.
Where exactly are your test runner and feature files? I've got the following setup which works perfectly:
src/test/
java/
com/mypackage/
TestRunner.java
StepDefinition.java
resources
com/mypackage/
fancy.feature
The Maven/Cuke conventions will have the tests executed from the tests/java directory and the feature files found in the test/resources directory. My test runner is basically the same as yours but with less options:
import cucumber.api.junit.Cucumber;
import org.junit.runner.RunWith;
#RunWith(Cucumber.class)
#Cucumber.Options(format = {"pretty"})
public class TestRunner { }
Hope this helps if you hadn't already found an answer.
I have a setup similar to yours (not using the Maven/Cucumber conventions). In my options, I don't specify the path from root, but from the project's source folder where the features are held. It makes sense, since otherwise the tests would only be runnable from your machine.
In your case, I think it should be:
features = "src/main/resources"
Just add features = { "classpath:features/feature.feature"}, and the feature must under test/resources/features/feature.feature.
#CucumberOptions(
format = {"pretty", "html:target/html"},
features = {"classpath:features/feature.feature"},
snippets = SnippetType.CAMELCASE
Note classpath.
When you compile your code if you are using maven open up target/test-classes/features and you will see feature.feature
//Removing the space between "**classpath**" and "**:com/**" helped.
#RunWith(Cucumber.class)
#CucumberOptions(
features = {"classpath:com/tk/feature/"}, //NOTE: NO SPACE
glue = {"classpath: com.tk.cucumber"},
plugin = {
"pretty",
"html:build/reports/cucumber"
,"json:build/reports/cucumber-tests/test.json"}
)
public class RunAPITests {}
If you are providing the complete path of the feature file i.e.
"C:/Users/sarthak.dayanand/Documents/WebRefreshTest/CukeAutomation/LebaraWebAutomationTest1/src/main/resources" as in your query, try again by replacing the '/' character with '\\'(double back slash) as below.
"C:\\Users\\sarthak.dayanand\\Documents\\WebRefreshTest\\CukeAutomation\\LebaraWebAutomationTest1\\src\main\\resources\\abc.feature"
This is a git repo which uses the latest cucumber version : Cucumber- Example
Clone this repo and run it in your local machine. The #Given is defined and it should pass. The #Then and #When should be shown as undefined.
This is how the output for it should look :
Output for the Belly feature
Use the structure mentioned :
src / test / java/ io /cucumber / {Step definitions java and run cucumber test files here}
src /test / resources/ io/ cucumber / {feature files here}
You can run the gradle build using ./gradlew clean build
and the cucumber test using ./gradlew clean test --info
If this works, then use the same format in your project.
Just changing .Feature to .feature the problem got resolved for me.
Also make sure the path for feature is righly mention in CucumberOptions as per your feature folder
Some of the online tutorial have mentioned .Feature which brings this problem
so changing the case will solve this problem
There is another instance in which 'Feature Not Found' error occurs. I am posting the solution under this answer as there is no similar question.
I got this error when trying to run the Runner file first time after setting up Cucumber project in Maven. The solution i found was as follows: Go to the folder in which the 'feature' file is present in Windows Explorer. Check the size of the feature file you are trying to run. If the size is '0' KB, it will show the 'Feature Not Found' error. Make some changes to file until a value greater than zero is displayed. Run again after making changes.
#RunWith(Cucumber.class)
#CucumberOptions(
features = {"src/main/resources/cucumber/features"},//your feature path
tags = "not #Wip",
glue = {"classpath:steps"},
plugin = {"pretty", "html:target/cucumber/html"})
You must set the feature directory correctly
By putting the feature file under src/test/java where the runner and steps file or
by putting it under src/main/java the problem will get resolved.

Groovy with Grape and AntBuilder classloader problem

I wanted to use groovy for a little ftp script and found this post http://www.hhhhq.org/blog/2009/05/01/ftp-using-groovy-and-ant/
Since there were several dependencies I wanted to use Grape. All dependencies are resolved and present in the cache. But I can't get Ant to find the optional tasks in the other libs.
It always says
Caught: : Problem: failed to create task or type ftp
Cause: the class org.apache.tools.ant.taskdefs.optional.net.FTP was not found.
This looks like one of Ant's optional components.
Action: Check that the appropriate optional JAR exists in
-ANT_HOME\lib
-the IDE Ant configuration dialogs
Do not panic, this is a common problem.
The commonest cause is a missing JAR.
This is not a bug; it is a configuration problem
at GrabTest.runMe(GrabTest.groovy:15)
at GrabTest.run(GrabTest.groovy:26)
Groovy Version: 1.6.5 JVM: 1.6.0_15
Here is my source code
#Grab(group='ant', module='ant', version='[1.6.5,)')
#Grab(group='ant', module='ant-nodeps', version='[1.0,)')
#Grab(group='ant', module='ant-apache-oro', version='[1.0,)')
#Grab(group='ant', module='ant-commons-net', version='[1.0,)')
#Grab(group='apache-oro', module='jakarta-oro', version='[2.0.8,)')
#Grab(group='commons-net', module='commons-net', version='[1.4,)')
def runMe() {
// works
println getClass().getClassLoader().loadClass("org.apache.tools.ant.taskdefs.optional.net.FTP")
def ant = new AntBuilder()
println getClass().getClassLoader() //groovy.lang.GroovyClassLoader$InnerLoader
println ant.getClass().getClassLoader() //org.codehaus.groovy.tools.RootLoader
ant.ftp( server:"ftp.foo.com",
userid:"user",
password:"passwd",
passive:"yes",
verbose:"yes",
remotedir:"/pub/incoming",
binary:"yes" ) {
fileset( dir:"." ) { include( name:"**/*.gz" ) }
}
}
runMe()
As you can see I suspect the classloader of being the problem, it seems that
Grape doesn't inject the dependencies there.
Any idea of how I can get it to work?
You're right suspecting the classloader to be the root of the problem. As your code already reveals, the AntBuilder is loaded from the RootLoader, that doesn't have access to the classes loaded by the #Grab annotation. As GROOVY-3730 shows, Groovy 1.7 is going to address this problem.
However, you can solve your problem by directly using the groovy.grape.Grape.grab(Map dependency) method, in which you can set a specific classloader that should be used to load the dependencies:
import groovy.grape.Grape;
Grape.grab(group:'ant', module:'ant', version:'1.6.5', classLoader:this.class.classLoader.rootLoader)
Grape.grab(group:'ant', module:'ant-nodeps', version:'1.6.5', classLoader:this.class.classLoader.rootLoader)
Grape.grab(group:'ant', module:'ant-apache-oro', version:'1.6.5', classLoader:this.class.classLoader.rootLoader)
Grape.grab(group:'ant', module:'ant-commons-net', version:'1.6.5', classLoader:this.class.classLoader.rootLoader)
Grape.grab(group:'commons-net', module:'commons-net', version:'1.4.1', classLoader:this.class.classLoader.rootLoader)
Grape.grab(group:'oro', module:'oro', version:'2.0.8', classLoader:this.class.classLoader.rootLoader)
Or just simply use
#GrabConfig(systemClassLoader=true)
Further info can be found: http://groovy.codehaus.org/Grape

Resources