groovy.lang.MissingPropertyException: No such property: - groovy

I am trying to get my head around groovy scripting to make some changes to a jenkins pipeline and I keep getting this error:
groovy.lang.MissingPropertyException: No such property: credentials for class:
I have tried declaring the variable with def but I still get the exception, eclipse does not recognise that the property exists.
What am I doing wrong?!
#!/usr/bin/groovy
package common.pipeline
import common.pipeline.Credentials
Credentials credentials = new Credentials()
def withCredentials(steps) {
credentials.productionPipeline(steps)
}

This script will be compiled by groovy into a Script class with the field definition inside the run method, and with another method withCredentials that is trying to access the field (kinda like this):
import common.pipeline.Credentials
class Script1 extends Script {
def withCredentials(steps) {
credentials.productionPipeline(steps)
}
def run(args) {
Credentials credentials = new Credentials()
}
}
As you can see, this won't work, as the credentials aren't at Field level in the class...
Groovy has an annotation to make this happen:
#!/usr/bin/groovy
package common.pipeline
import common.pipeline.Credentials
import groovy.transform.Field
#Field Credentials credentials = new Credentials()
def withCredentials(steps) {
credentials.productionPipeline(steps)
}

Related

Groovy call another script to set variables

I'm trying to define variables in another groovy script that I want to use in my current script. I have two scripts like this:
script1.groovy
thing = evaluate(new File("script2.groovy"))
thing.setLocalEnv()
println(state)
script2.groovy
static def setLocalEnv(){
def state = "hi"
def item = "hey"
}
When I println(state), I get a missing property exception. Basically I want script2 to have config variables that I can load in the context of script1. How can I do this?
I'm not sure what/how you want to do exactly, but I guess you can achieve your goal using one of the class available in groovy dynamique scripting capabilities: groovy.lang.Binding or GroovyClassLoader or GroovyScriptEngine, here is an example using GroovyShell class:
abstract class MyScript extends Script {
String name
String greet() {
"Hello, $name!"
}
}
import org.codehaus.groovy.control.CompilerConfiguration
def config = new CompilerConfiguration()
config.scriptBaseClass = 'MyScript'
def shell = new GroovyShell(this.class.classLoader, new Binding(), config)
def script = shell.parse('greet()')
assert script instanceof MyScript
script.setName('covfefe')
assert script.run() == 'Hello, covfefe!'
This is one way to bind a variable to an external script file, more examples from the doc:
http://docs.groovy-lang.org/latest/html/documentation/guide-integrating.html
P.S. Loading external file can be done with GroovyClassLoader:
def gcl = new GroovyClassLoader()
def clazz2 = gcl.parseClass(new File(file.absolutePath))
Hope this helps.

jenkins pipeline groovy.sql.Sql NotSerializableException

there is a problem with the class groovy.sql.Sql inside jenkinsfile.
We are using groovy.sql.Sql to call DB.
Try with simple import groovy.sql.Sql we are take error:
java.io.NotSerializableException: groovy.sql.Sql
Then, try to hide this class inside shell class in jenkins file, like this:
class Shell{
private groovy.sql.Sql sql
Shell(){
sql = Sql.newInstance("jdbc:oracle:thin:#$TNS", login, password, driver)
}
String callSql(String stmnt){
return sql.firstRow(stmnt).Variablename
}
}
But get another error "MissingPropertyException: No such property: Sql for class".
Can u help to fix this problem?

Spock test showing groovy.lang.MissingPropertyException

I have the following spock test. I am first going to the login page, and then I am clicking the login button without entering an email and password to verify the error message. I will add other steps later such as email but no password and email with incorrect password, but I first need to get this test to work.
package loginPageTests
import Pages.loginPage
import geb.Page
import geb.spock.GebReportingSpec
class invalidLoginSpec extends GebReportingSpec {
def "Go to login page"() {
when:
Page loginPage = to loginPage
waitFor { loginPage.loginButton.isDisplayed() }
then:
at loginPage
}
def "Try to log in without email or password"() {
when:
loginPage.loginButton.click()
then:
at loginPage
assert loginPage.loginError.text() == "Please enter your email and password."
}
}
And the following page object
package Pages
import geb.Page
class loginPage extends Page {
static url = 'login/'
static at = { title == "Login to TB"}
static content = {
loginButton {$("#loginButton")}
loginError(wait:true) {$("#loginError")}
}
}
The first method runs successfully, but I get this error when the second method tries to run
groovy.lang.MissingPropertyException: No such property: loginButton
for class: Pages.loginPage
the property loginButton is in the loginPage page object, so I'm not sure why this error is occurring.
The way you are interacting with the page is non-idiomatic but to answer the question asked...
You have defined loginPage as a local variable inside of the first test method and then tried to reference it inside of the second test method where it is out of scope.

How to get a user by email in JIRA Script Runner

When writing a Groovy script for JIRA Script Runner, how do you get a user, or just their username, given their email address?
It seems that you're supposed to use the findUsersByEmail method in the UserSearchService interface.
https://docs.atlassian.com/jira/7.0.2/com/atlassian/jira/bc/user/search/UserSearchService.html
But how do you get an instance of this class?
Related question: How to get a user by email in a JIRA plugin.
The difference is that question is about a plugin, and my question is about JIRA Script Runner.
This code does not work:
setUserProperties(httpMethod: "POST", groups: ["jira-administrators"])
{ MultivaluedMap queryParams, String body, HttpServletRequest request ->
def userPropertyManager = ComponentAccessor.getUserPropertyManager()
def userManager = ComponentAccessor.getUserManager()
def userSearchService = DefaultUserPickerSearchService;
def users = userSearchService.findUsersByEmail("felicity.smoak#queenconsolidated.com")
users.each {
aUser ->
userPropertyManager.getPropertySet(aUser).setString("jira.meta.Company", "Smoak Technologies")
}
return Response.ok(users).build();
}
This is the error I got:
2016-04-18 15:23:06,168 ERROR [common.UserCustomScriptEndpoint]: *************************************************************************************
2016-04-18 15:23:06,168 ERROR [common.UserCustomScriptEndpoint]: Script endpoint failed on method: POST setUserProperties
groovy.lang.MissingMethodException: No signature of method: static com.atlassian.jira.bc.user.search.DefaultUserPickerSearchService.findUsersByEmail() is applicable for argument types: (java.lang.String) values: [felicity.smoak#queenconsolidated.com]
Possible solutions: findUsersByEmail(java.lang.String), findUserKeysByEmail(java.lang.String)
at Script462$_run_closure3.doCall(Script462.groovy:40)
at com.onresolve.scriptrunner.runner.rest.common.UserCustomScriptEndpoint.doEndpoint(UserCustomScriptEndpoint.groovy:308)
at com.onresolve.scriptrunner.runner.rest.common.UserCustomScriptEndpoint.postUserEndpoint(UserCustomScriptEndpoint.groovy:208)
EDIT
Based on #Oldskultxo's and #BjörnKautler suggestions, this is now my working code:
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.ComponentManager
import com.atlassian.jira.user.*
import com.atlassian.jira.bc.user.search.UserSearchService
import com.atlassian.sal.api.user.UserManager
import com.onresolve.scriptrunner.runner.rest.common.CustomEndpointDelegate
import groovy.json.*
import groovy.transform.BaseScript
import javax.servlet.http.HttpServletRequest
import javax.ws.rs.core.MultivaluedMap
import javax.ws.rs.core.Response
#BaseScript CustomEndpointDelegate delegate
setUserProperties(httpMethod: "POST", groups: ["jira-administrators"])
{ MultivaluedMap queryParams, String body, HttpServletRequest request ->
def userPropertyManager = ComponentAccessor.getUserPropertyManager()
def userManager = ComponentAccessor.getUserManager()
def userSearchService = ComponentAccessor.getComponent(UserSearchService.class)
def users = userSearchService.findUsersByEmail("felicity.smoak#queenconsolidated.com")
users.each {
aUser ->
userPropertyManager.getPropertySet(aUser).setString("jira.meta.Company", "Smoak Technologies")
}
return Response.ok("200").build();
}
Use ComponentAccessor.getComponent(UserSearchService) to get the right service if there is no concrete getUserSearchService() method.
I usually get components this way:
ComponentManager.getComponentInstanceOfType(UserSearchService.class);
And then just look for its methods.
Regards

null object error when calling code from script assertion - soapui (creating test Runner in script assertion)

In a soapui groovy script test step I've this.
context.setProperty("searchA", new searchA());
class searchA{
def testRunner
def searchA(testRunner){
this.testRunner=testRunner
}
def search(a,b){
def search_TestCase = testRunner.testCase.testSuite.getTestCaseByName("Search")
search_TestCase.setPropertyValue("ABC", a)
search_TestCase.setPropertyValue("DEF", b)
search_TestCase.run(new com.eviware.soapui.support.types.StringToObjectMap(), false)
}
}
and in an assertion script in a different test suite I am calling the above code like this.
scripts = messageExchange.modelItem.testStep.testCase.testSuite.project.testSuites["Test"]
scripts.testCases["Lib123"].testSteps["TestLib123"].run(context.getTestRunner(),context)
context.searchA.search("value1","value2")
but this gives me error "can not get property testCase on null object". whats wrong here?
I am not seeing null object error now. The issue was that testRunner is not available in script assertion so we need to create it like this in script assertion and then pass it in the caller method.
import com.eviware.soapui.impl.wsdl.testcase.WsdlTestCaseRunner
import com.eviware.soapui.support.types.StringToObjectMap
import com.eviware.soapui.impl.wsdl.testcase.WsdlTestRunContext
testCase = messageExchange.modelItem.testStep.testCase
tcRunner = new WsdlTestCaseRunner( testCase, new StringToObjectMap() );
context.searchA.search("value1","value2",tcRunner)
This thread helped me.

Resources