Groovy exception - groovy

Please help. I can't understand whats wrong with my script.
import org.apache.log4j.Category
import com.atlassian.jira.ComponentManager
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.jql.builder.JqlQueryBuilder
import com.atlassian.jira.event.type.EventDispatchOption
import com.atlassian.jira.issue.MutableIssue
import java.util.Date
import java.util.Calendar
import com.atlassian.jira.bc.JiraServiceContextImpl
import com.atlassian.jira.web.bean.PagerFilter
import com.atlassian.jira.issue.Issue
import java.util.List
import com.atlassian.jira.issue.IssueInputParameters
import com.atlassian.jira.user.util.UserManager
import com.atlassian.jira.user.ApplicationUser
import com.atlassian.crowd.embedded.api.CrowdService
import com.atlassian.crowd.embedded.api.User
def Category log = Category.getInstance("com.onresolve.jira.groovy.PostFunction")
log.setLevel(org.apache.log4j.Level.DEBUG)
def user = ComponentAccessor.getJiraAuthenticationContext().getLoggedInUser()
def ctx = new JiraServiceContextImpl(user)
def searchRequestService = ComponentManager.getInstance().getSearchRequestService()
def searchProvider = ComponentManager.getInstance().getSearchProvider()
def sr = searchRequestService.getFilter(ctx, 17540)
def searchResult = searchProvider.search(sr?.getQuery(), user, PagerFilter.getUnlimitedFilter())
def issueManager = ComponentManager.getInstance().getIssueManager()
def issues = searchResult.getIssues().collect {issueManager.getIssueObject(it.id)}
for ( issue in issues ){
issueInputParameters issueToCreate = ComponentAccessor.getIssueService().newIssueInputParameters();
issueToCreate.setSummary("This is a test.");
issueToCreate.setDescription("Testing issue creation");
issueToCreate.setAssigneeId(user.getName());
issueService.createValidationResult validationResult = ComponentAccessor.getIssueService().validateCreate(user, issueToCreate);
if(!validationResult.isValid()){
for(String registeredErrorMessage:validationResult.getErrorCollection().getErrors().values())
{
printx "Failed"
}
}
else {
issueService.issueResult createdIssue = ComponentAccessor.getIssueService().create(user, validationResult);
}
}
return issues
I get the next excetpion :
groovy.lang.MissingMethodException: No signature of method:
org.codehaus.groovy.jsr223.GroovyScriptEngineImpl.issueInputParameters()
is applicable for argument types:
(com.atlassian.jira.issue.IssueInputParametersImpl) values:
[com.atlassian.jira.issue.IssueInputParametersImpl#6cde0354] at
Script87.run(Script87.groovy:34)
Thank you.

Shouldn't the issueInputParameters in this line be capitialized - IssueInputParameters:
issueInputParameters issueToCreate = ComponentAccessor.getIssueService().newIssueInputParameters();

Related

Trying to mock two classes with Groovy Spock Mock: GroovyCastException

I try to mock two classes in a Jenkins Pipeline var-script, but however I order the definition of the Mock I receive a GroovyCastException, while the mock for the second class is initiated
org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'Mock for type 'ClassA'' with class 'com.pipeline.ClassA$$EnhancerByCGLIB$$9b005c28' to class 'com.pipeline.DBReader'
This is how my Spock-Test looks like:
import com.homeaway.devtools.jenkins.testing.JenkinsPipelineSpecification
import com.pipeline.ClassA
import com.pipeline.DBReader
import groovy.sql.Sql
import org.jenkinsci.plugins.workflow.steps.FlowInterruptedException
import hudson.model.Result
class execScriptSpec extends JenkinsPipelineSpecification {
def execPipelineScript = null
def mockStage = [timeout: [time: 'mocktime']]
def mockScript = [...]
def setup() {
execPipelineScript = loadPipelineScriptForTest("vars/execScript.groovy")
}
def "Test Pipeline-Script"() {
setup:
GroovyMock(ClassA, global: true)
new ClassA(*_) >> Mock(ClassA) {
loadScope(_) >> null
loadJsonFromURL(_) >> null
}
GroovyMock(DBReader, global: true)
new DBReader(*_) >> Mock(DBReader) {
loadDBDriver(_) >> null
}
when:
execPipelineScript(mockScript, mockStage)
then:
true
And that is the code under test:
import com.pipeline.DBReader
import com.pipeline.ClassA
def call(script, stage) {
def pipelineConfig = script.pipelineConfig
def stageStatus = pipelineConfig.general.stageStatus
def projectName = script.env.project
// DB connection parameters
def dbName = script.deliveryConfig.system.dbName
def dbSchema = script.deliveryConfig.system.dbSchema
def dbServer = script.deliveryConfig.system.dbServer
def dbUser = script.deliveryConfig.system.dbUser
// DB Driver to use
def dbDriver = script.deliveryConfig.system.dbDriver
def dbPassword = script.env.password
// Create new DB-Client
DBReader dbClient = new DBReader(dbName, dbSchema, dbServer, dbUser, dbPassword, dbDriver)
dbClient.loadDBDriver()
def contextParameter = script.params['Context']
ClassA mapGavToVersionRange = new ClassA(projectName, contextParameter, script)
classAInstance.loadDeliveryScope( dbClient )
def url = 'https://some.valid.url'
classAInstance.loadJsonFromURL(url)
...
So don't get me wrong: The actual mocking of one or the other class works (if I put only one of them in my test), but as soon as I put both of them, the second one will not work. And I currently have no idea, why this happens.
Would be great, if anybody has an idea :-)
Thanks a lot!

Calling a function periodically in Scala while another expensive function is computing

I have a function that takes a long time to compute
def longFunc = {Thread.sleep(30000); true}
while this function is computing, I'd need to ping a server so it keeps waiting for the value of my function. But for the sake of the argument let's say I need to run the following function every 5 seconds while my longFunc is running
def shortFunc = println("pinging server! I am alive!")
To do this I have the following snippet and it works but I wonder if there is a better pattern for this scenario
import scala.concurrent.{Await, Future}
import scala.concurrent.duration._
import java.util.{Timer, TimerTask}
import scala.concurrent.ExecutionContext.Implicits.global
def shortFunc = println("pinging server! I am alive!")
def longFunc = {Thread.sleep(30000); true}
val funcFuture = Future{longFunc}
val timer = new Timer()
def pinger = new TimerTask {
def run(): Unit = shortFunc
}
timer.schedule(pinger, 0L, 5000L) // ping the server every two minutes to say you are still working
val done = Await.result(funcFuture, 1 minutes)
pinger.cancel
I'm not actually sure if this is more elegant pattern or just for fun:
import scala.concurrent.{Await, Future}
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global
def waiter[T](futureToWait:Future[_], waitFunc: => T, timer: Duration) = Future {
while (!futureToWait.isCompleted) {
Try(Await.ready(futureToWait, timer))
waitFunc
}
}
def longFunc = {Thread.sleep(30000); true}
def shortFunc = println("pinging server! I am alive!")
val funcFuture = Future{longFunc}
waiter(funcFuture,shortFunc,5 second)
val done = Await.result(funcFuture, 1 minutes)
The same but shorter:
import scala.concurrent.{Await, Future}
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global
def longFunc = {Thread.sleep(30000); true}
def shortFunc = println("pinging server! I am alive!")
val funcFuture = Future{longFunc}
def ff:Future[_] = Future{
shortFunc
Try(Await.ready(funcFuture, 5 second)).getOrElse(ff)
}
ff
val done = Await.result(funcFuture, 1 minutes)

GitBlit add a hook

I have a GitBlit instance on a windows server, and i want to set a hook on post receive callback to start a gitlab ci pipeline on another server.
I already have set a GitlabCi trigger who works well, but my hook doesn't. Here is build-gitlab-ci.groovy file :
import com.gitblit.GitBlit
import com.gitblit.Keys
import com.gitblit.models.RepositoryModel
import com.gitblit.models.UserModel
import com.gitblit.utils.JGitUtils
import org.eclipse.jgit.lib.Repository
import org.eclipse.jgit.revwalk.RevCommit
import org.eclipse.jgit.transport.ReceiveCommand
import org.eclipse.jgit.transport.ReceiveCommand.Result
import org.slf4j.Logger
logger.info("Gitlab-CI hook triggered by ${user.username} for ${repository.name}")
// POST :
def sendPostRequest(urlString, paramString) {
def url = new URL(urlString)
def conn = url.openConnection()
conn.setDoOutput(true)
def writer = new OutputStreamWriter(conn.getOutputStream())
writer.write(paramString)
writer.flush()
String line
def reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))
while ((line = reader.readLine()) != null) {
println line
}
writer.close()
reader.close()
}
sendPostRequest("https://xxxxx/api/v4/projects/1/trigger/pipeline", "token=xxxxxxxx&ref=master")
The project configuration :
Moreover, i don't know where logger.info write the log, so i don't know if my script was executed well. Thanks for help
I found my problem, it was a SSL self-certificate problem. I added this code to ignore it :
import com.gitblit.GitBlit
import com.gitblit.Keys
import com.gitblit.models.RepositoryModel
import com.gitblit.models.UserModel
import com.gitblit.utils.JGitUtils
import org.eclipse.jgit.lib.Repository
import org.eclipse.jgit.revwalk.RevCommit
import org.eclipse.jgit.transport.ReceiveCommand
import org.eclipse.jgit.transport.ReceiveCommand.Result
import org.slf4j.Logger
logger.info("Gitlab-CI hook triggered by ${user.username} for ${repository.name}")
def nullTrustManager = [
checkClientTrusted: { chain, authType -> },
checkServerTrusted: { chain, authType -> },
getAcceptedIssuers: { null }
]
def nullHostnameVerifier = [
verify: { hostname, session -> hostname.startsWith('yuml.me')}
]
javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL")
sc.init(null, [nullTrustManager as javax.net.ssl.X509TrustManager] as javax.net.ssl.X509TrustManager[], null)
javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory())
javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(nullHostnameVerifier as javax.net.ssl.HostnameVerifier)
def url = new URL("https://xxxx/api/v4/projects/{idProject}/trigger/pipeline")
def conn = url.openConnection()
conn.setDoOutput(true)
def writer = new OutputStreamWriter(conn.getOutputStream())
writer.write("token={token}&ref={branch}")
writer.flush()
String line
def reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))
while ((line = reader.readLine()) != null) {
println line
}
writer.close()
reader.close()
And I identified the error checking the logs in E:\gitblit-1.7.1\logs\gitblit-stdout.{date}.log.
NB : stdout file date can be very old. Gitblit doesn't create a file per day. Mine had a name expired 4 months ago.

SOAPUI - Groovy scripting - jsonBuilder strips quotes

I have a problem where jsonBuilder strips quotes from the result string. How do I format the output to return a JSON response with quotes ?
import com.eviware.soapui.support.XmlHolder
import net.sf.*
import net.sf.json.*
import net.sf.json.groovy.*
import groovy.json.JsonSlurper
import groovy.json.JsonBuilder
import groovy.json.*
import groovy.json.JsonOutput
import net.sf.json.JSONObject
def ResponseMessage = testRunner.testCase.testSteps["MerchantEMS_POST"].testRequest.response.contentAsString
def jsonSlurper = new JsonSlurper().parseText(ResponseMessage)
log.info ResponseMessage
def merchantResult = ResponseMessage
def newMerchantID = "60300004055"
def entityID = jsonSlurper.entityId
jsonSlurper.merchantId = newMerchantID
def jsonBuilder = new groovy.json.JsonBuilder()
def updatedjson = jsonBuilder(jsonSlurper)
log.info "updated JSON = $updatedjson"
return updatedjson
ResponseMessage : { "entityId" : "93LSHLXW7BJ5K00MJALWZJMLL0", "creatorId" : "HPCDKMSV763K2VGHCKQQ09QSGM", "createdTimestamp" : "2015-09-02T00:26:34.015Z", "updaterId" : "HPCDKMSV763K2VGHCKQQ09QSGM", "updatedTimestamp" : "2015-09-02T00:26:34.015Z", "merchantId" : "L7QWKA0001F5W1RRZY4Z006153",
"createdBy" : "ralgg00", "isDeleted" : false }
updatedjson (no quotes) = [updatedTimestamp:2015-09-02T00:26:34.015Z, createdBy:ralgg00, createdTimestamp:2015-09-02T00:26:34.015Z, creatorId:HPCDKMSV763K2VGHCKQQ09QSGM, entityId:93LSHLXW7BJ5K00MJALWZJMLL0, merchantId:60300004055, isDeleted:false, updaterId:HPCDKMSV763K2VGHCKQQ09QSGM]
EDIT:
When you log the 'updatedjson' it recognises it as Map object and prints its fields. You need to use something that can convert a Map object to JSON and print it out. There are many ways to do this, for example:
def json = JsonOutput.toJson(updatedjson)
println json
Source: http://www.groovy-lang.org/json.html

Updating JSON Data with Groovy's HTTP Builder using PUT

I have requirement of updating Zendesk Tickets using Groovy HTTP Builder. I use the following code
#Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.5.0-RC2' )
import java.util.Properties;
import java.io.InputStream;
import java.io.ByteArrayInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import groovyx.net.http.*;
import static groovyx.net.http.Method.*;
import groovy.json.*;
import groovyx.net.http.ContentType;
def jsonBuilder = new groovy.json.JsonBuilder();
class MyTicket
{
def subject
}
def myTicket = new MyTicket(
subject: 'xyz'.toString()
)
def ticketList=[myTicket]
jsonBuilder(ticket:ticketList)
println(jsonBuilder)
def authSite = new HTTPBuilder('https://{subdomain}.zendesk.com/api/v2/tickets/{ticketid}.json');
authSite.auth.basic 'username', 'password';
authSite.request( Method.PUT, ContentType.JSON )
{ req ->
uri.path = ''https://{subdomain}.zendesk.com/api/v2/tickets/{ticketid}.json'';
requestContentType = ContentType.JSON;
headers.Accept = 'application/json';
body =[jsonBuilder]
response.success = { resp, reader->
reader.ticket.subject;
}
}
But the ticket is not being updated. Is there any kind of execute method. Kindly Suggest me where I went wrong.
Try this, you'll need to set up your subdomain, ticketid, user and pass (I've removed all the unnecessary imports as well):
#Grab( 'org.codehaus.groovy.modules.http-builder:http-builder:0.6' )
import groovyx.net.http.HTTPBuilder
import static groovyx.net.http.Method.PUT
import static groovyx.net.http.ContentType.JSON
def subdomain = 'woo'
def ticketid = '123'
def authSite = new HTTPBuilder("https://${subdomain}.zendesk.com/api/v2/tickets/${ticketid}.json");
authSite.auth.basic( 'user', 'pass' )
authSite.request( PUT, JSON ) { req ->
body = [ ticket:[ subject: 'xyz' ] ]
response.success = { resp, json ->
println "Success! ${resp.status}"
}
response.failure = { resp ->
println "Request failed with status ${resp.status}"
}
}

Resources