Update Insight Custom field => cannot be cast to java.util.Collection' - groovy

I have a strange problem. My script is practically finished.
To understand the script : In Insight, I have all our servers object created automatically.
We use a monitoring called Centreon, this monitoring send an email to the service desk mailbox automatically when a error occur and a ticket is created. I want to add the corresponding object to the corresponding server.
The name of the server is present in the summary of the email;
Example : AFDAOS.xxx.int problem alert
A groovy script check the name of the server, if it found a correspond name (in the FQDN Attribute), the object is affected to the ticket.
All code working until the updating of the ticket, i have a statement where all objects are checked, when i found the good object (string currentobject), i want to update the current issue with this object i have the error :
GroovyInsightException: com.riadalabs.jira.plugins.insight.services.model.ObjectBean cannot be cast to java.util.Collection'
BUT if I replace currentobject by Objects (I suppose it's an array), the ticket is updating with all objects without any error. I understand that I can only update the ticket with an array and not a unique value... I don't found the good way to do it... Thank you for your help.
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.fields.CustomField
import com.riadalabs.jira.plugins.insight.services.model.CommentBean;
import com.atlassian.jira.issue.MutableIssue
import com.atlassian.jira.event.type.EventDispatchOption
import com.riadalabs.jira.plugins.insight.channel.external.api.facade.ObjectFacade
import com.riadalabs.jira.plugins.insight.services.model.ObjectAttributeBean
import com.riadalabs.jira.plugins.insight.services.model.ObjectBean
import groovy.transform.ToString
Class objectFacadeClass = ComponentAccessor.getPluginAccessor().getClassLoader().findClass("com.riadalabs.jira.plugins.insight.channel.external.api.facade.ObjectFacade");
def objectFacade = ComponentAccessor.getOSGiComponentInstanceOfType(objectFacadeClass);
//CustomField jiraCustomField = ComponentAccessor.getCustomFieldManager().getCustomFieldObject(12124);
CustomField insightCF = ComponentAccessor.getCustomFieldManager().getCustomFieldObject(12124);
Class iqlFacadeClass = ComponentAccessor.getPluginAccessor().getClassLoader().findClass("com.riadalabs.jira.plugins.insight.channel.external.api.facade.IQLFacade");
def iqlFacade = ComponentAccessor.getOSGiComponentInstanceOfType(iqlFacadeClass);
def objects = iqlFacade.findObjectsByIQLAndSchema(10,"objectTypeId = 2443");
//def test = "AF-172738"
//def ObjectInsightBean = objectFacade.loadObjectBean(test)
//log.warn("ObjectInsightBean " + ObjectInsightBean)
def n = 0
(objects).each {
CurrentObject = objects[n]
def fqdnvalue = objectFacade.loadObjectAttributeBean(CurrentObject.getId(),47464).getObjectAttributeValueBeans()[0]; //Load Attribute Value
def fqdn_string = fqdnvalue.toString()
def fqdn_string_split = fqdn_string.split("\\(");
def fqdn_string_split_1 = fqdn_string_split[1]
def fqdn_string_split_2 = fqdn_string_split_1.substring(0, fqdn_string_split_1.length() - 2);
result = (issue.getSummary().contains(fqdn_string_split_2)) // if the value fqdn_string_split_2 present in the summary => result = true
if (result==true){
log.info("Statement " + "True" + CurrentObject);
MutableIssue mi = (MutableIssue) issue;
mi.setCustomFieldValue(insightCF, CurrentObject); // => Work if i replace CurrentObject by objects
ComponentAccessor.getIssueManager().updateIssue(currentUser, mi, EventDispatchOption.DO_NOT_DISPATCH, false); // Error GroovyInsightException: com.riadalabs.jira.plugins.insight.services.model.ObjectBean cannot be cast to java.util.Collection'
}
log.info("fqdn_string_split_2 " + fqdn_string_split_2)
log.info("Result " + result)
n ++
return result;
}
Solved by converting the string into List:
if (result==true){
//log.info("Statement " + "True" + CurrentObject);
MutableIssue mi = (MutableIssue) issue;
def CurrentObject_list = [CurrentObject];
log.info("List " + CurrentObject_list);
mi.setCustomFieldValue(insightCF, CurrentObject_list); // => Work if i replace CurrentObject by objects
ComponentAccessor.getIssueManager().updateIssue(currentUser, mi, EventDispatchOption.DO_NOT_DISPATCH, false); // Error GroovyInsightException: com.riadalabs.jira.plugins.insight.services.model.ObjectBean cannot be cast to java.util.Collection'
}
//log.info("fqdn_string_split_2 " + fqdn_string_split_2)
//log.info("Result " + result)
n ++
return result;

Related

Scriptrunner Create issue and assign to existing epic

While creating a new issue using scriptrunner, I would like to assign it an existing epic. it seems the issue.setCustomFieldValue(epicLinkCustomField) is not working. any help would be greatly appreciated. everything else works fine, im able to set name, summary, tittle, prio, description, assign reporter, projectkey, issue context, and issue type.
The code I have is below.
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.context.IssueContext
import com.atlassian.jira.issue.context.IssueContextImpl
import com.atlassian.jira.issue.fields.config.manager.PrioritySchemeManager
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.IssueManager
import com.atlassian.jira.issue.Issue
import com.atlassian.jira.issue.CustomFieldManager
import com.atlassian.jira.issue.MutableIssue
import java.text.SimpleDateFormat
def date = new Date()
def sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss")
// the project key under which the issue will get created
final projectKey = 'SEC'
// stores status
final statusKey = 'AN QUE'
// the issue type for the new issue
final issueTypeName = 'Task'
// user with that user key will be the reporter of the issue
final reporterKey = 'MV108788'
// the summary of the new issue
final summary = 'test' + date
// the priority of the new issue
final priorityName = 'Low'
// sets description
final description = 'this is a decription'
//epic
final epicIssueKey = 'test'
def issueService = ComponentAccessor.issueService
def constantsManager = ComponentAccessor.constantsManager
def loggedInUser = ComponentAccessor.jiraAuthenticationContext.loggedInUser
def prioritySchemeManager = ComponentAccessor.getComponent(PrioritySchemeManager)
//finds epic
def epicLinkCustomField = ComponentAccessor.customFieldManager.getCustomFieldObjects().findByName(epicIssueKey)
//finds status key
def status = ComponentAccessor.constantsManager.getStatusByName(statusKey)
//finds project key
def project = ComponentAccessor.projectManager.getProjectObjByKey(projectKey)
assert project : "Could not find project with key $projectKey"
//finds issue types
def issueType = constantsManager.allIssueTypeObjects.findByName(issueTypeName)
assert issueType : "Could not find issue type with name $issueTypeName"
// if we cannot find user with the specified key or this is null, then set as a reporter the logged in user
def reporter = ComponentAccessor.userManager.getUserByKey(reporterKey) ?: loggedInUser
// if we cannot find the priority with the given name or if this is null, then set the default priority
def issueContext = new IssueContextImpl(project, issueType) as IssueContext
// finds priority
def priorityId = constantsManager.priorities.findByName(priorityName)?.id ?: prioritySchemeManager.getDefaultOption(issueContext)
//sets all issue settings
def issueInputParameters = issueService.newIssueInputParameters().with {
setStatusId(statusId) //not working
setProjectId(project.id)
setDescription(description)
setIssueTypeId(issueType.id)
setReporterId(reporter.name)
setSummary(summary)
setPriorityId(priorityId)
issue.setCustomFieldValue(epicLinkCustomField)
}
def validationResult = issueService.validateCreate(loggedInUser, issueInputParameters)
assert validationResult.valid : validationResult.errorCollection
def result = issueService.create(loggedInUser, validationResult)
assert result.valid : result.errorCollection

Asserting object count in a JSON response using groovy script

I have a question on how to assert the element_count equals to the number of objects from response.
The link to the API is https://api.nasa.gov/neo/rest/v1/feed?start_date=2019-05-10&end_date=2019-05-16&api_key=*******
I tried using the below code but did not have any luck trying to count the objects from the JSON response using grrovy script.
import groovy.json.JsonSlurper
def ResponseMessage = messageExchange.response.responseContent
def response = new JsonSlurper().parseText(ResponseMessage)
def elementCount = response.element_count
def idCount = response.count { it.equals('neo_reference_id') }
I was trying to count the number of neo_reference_id which should equal element_count. Any help would be great.
def url = new URL('https://api.nasa.gov/neo/rest/v1/feed?start_date=2019-05-10&end_date=2019-05-16&api_key=***')
def response = new groovy.json.JsonSlurper().parse( url )
def neo_references = response.near_earth_objects.collectMany{date,objects-> objects.collect{it.neo_reference_id} }
println neo_references
println neo_references.size()
assert response.element_count == neo_references.size()

Nexus 3 Query builder how to retrieve artefacts in descending order

Is there a way we can retrieve artefacts in date descending order?
I currently have below script here as an example:
import org.sonatype.nexus.repository.storage.Asset
import org.sonatype.nexus.repository.storage.Query
import org.sonatype.nexus.repository.storage.StorageFacet
import groovy.json.JsonOutput
import groovy.json.JsonSlurper
def request = new JsonSlurper().parseText(args)
assert request.groupId: 'groupId parameter is required'
assert request.repoName: 'repoName parameter is required'
assert request.startDate: 'startDate parameter is required, format: yyyy-mm-dd'
log.info("Gathering Asset list for repository: ${request.repoName} as of startDate: ${request.startDate}")
def repo = repository.repositoryManager.get(request.repoName)
StorageFacet storageFacet = repo.facet(StorageFacet)
def tx = storageFacet.txSupplier().get()
tx.begin()
Iterable<Asset> assets = tx.
findAssets(Query.builder()
.where('group = ').param(request.groupId)
.and('last_updated > ').param(request.startDate)
.build(), [repo])
def urls = assets.collect { "/repository/${repo.name}/${it.name()}" }
tx.commit()
def result = JsonOutput.toJson([
assets : urls,
since : request.startDate,
repoName: request.repoName
])
return result
with:
Query.builder()
.where('group = ').param(request.groupId)
.and('last_updated > ').param(request.startDate)
.build()
def urls = assets.collect { "/repository/${repo.name}/${it.name()}" }
Is there a way we can change above script to retrieve things in date descending order?
You can simply add a suffix.
Query.builder()
.where('group = ').param(request.groupId)
.and('last_updated > ').param(request.startDate)
.suffix('order by last_updated desc')
.build()
def urls = assets.collect { "/repository/${repo.name}/${it.name()}" }
Nexus is using OrientDB behind the scene. You can find query examples here:
https://orientdb.com/docs/2.0/orientdb.wiki/Tutorial-SQL.html

How to pick the particular row value from spock table

I have to Store multiple data's in the spock table . When ever required i have to pass the data through parameter value, according to that it should search in the spock table, pick corresponding data. Please see the code and correct it.
It would be very much helpful to me to implement my project.
def passW = "Publisher"
def "getPassword" (passW) {
expect:
if (secureKeyword == passW ) {
println "Result is " + encryptPass
}
where:
secureKeyword || encryptPass
"Author" || "aW50ZWxAMTIzNCE="
"Publisher" || "tsdwerDhV76wYCf="
}
Result should be : ​tsdwerDhV76wYCf=​
You can store module data in the static (or #Shared) collection and filter test input in where section in findAll closure.
def static moduleCredentials = ["Author":"aW50ZWxAMTIzNCE=",
"Publisher":"tsdwerDhV76wYCf="]
#Unroll
def "Module #module.key login credentials test"(){
def moduleName = module.key
def modulePass = module.value
println(moduleName+":"+modulePass)
expect:
assert modulePass
where:
module << moduleCredentials.findAll {it.key=="Author"}.entrySet()
}

addAssertion() not recognizing string value of "Contains" type

I have a groovy script that I've added code to to check if a value exists in an XML response I'm getting within SoapUI. I've been dealing with this for a few days and could use some help.
Here is the code:
import com.eviware.soapui.support.XmlHolder
import com.eviware.soapui.impl.wsdl.teststeps.registry.RestRequestStepFactory
// read your request template
def requestFile = new File("C:/XMLRequestScript/file.xml");
// parse it as xml
def requestXml = new XmlHolder(requestFile.text)
// get the current testCase to add testSteps later
def tc = testRunner.testCase;
// get the testStep as template to create the other requests
def tsTemplate = tc.getTestStepByName("Template");
// loop to create # of testSteps for each application
for(int i = 1; i < 3; i++) {
// xpath expression to get applicationNumber attribute in root node
def xpathNodeAttr = "/*/#ApplicationNumber";
// get the root node attribute applicationNumber throught an XPATH
int appId = Integer.parseInt(requestXml.getNodeValue(xpathNodeAttr));
// add 1 to appId
appId++;
// set the value again in the attribute
requestXml.setNodeValue(xpathNodeAttr,appId);
// create next testStepName for new Application
def testStepName = "TestStep_ApplicationNumber_" + String.valueOf(appId)
log.info testStepName;
log.info testStepName.getClass().getName()
log.info tc.getClass().getName()
// create a new testStepConfig
def testStepFactory = new RestRequestStepFactory();
def testStepConfig = testStepFactory.createConfig( tsTemplate.getTestRequest(), testStepName )
// add the new testStep to TestCase
def newTestStep = tc.insertTestStep( testStepConfig, -1 )
// set the request
newTestStep.getTestRequest().setRequestContent(requestXml.getXml())
// add Assertions here
def assertion = tc.getTestStepByName(newTestStep.toString()).addAssertion("Contains")
if (assertion.contains("Champion5")) {
newTestStep.addAssertion("Champion5")
log.info("REST response assertion created into: " + newTestStep)
} else {
log.info("REST response assertion not found in " + newTestStep)
}
if (assertion.contains("Challenger5")) {
newTestStep.addAssertion("Challenger5")
log.info("REST response assertion created into: " + newTestStep)
} else {
log.info("REST response assertion not found in " + newTestStep)
}
// execute the request
newTestStep.run(testRunner, context)
}
In the section above called "// add Assertions here", the line of code that I'm having a problem with is:
def assertion = tc.getTestStepByName(newTestStep.toString()).addAssertion("Contains")
The error states:
Thu Sep 18 14:27:57 CDT 2014:ERROR:An error occurred [Cannot invoke method addAssertion() on null object], see error log for details
My understanding is that I have to pass an Assertion Type that is contained in the SoapUI GUI and just put it in as a string value in order to check if the values that I'm checking are asserted.
Any suggestions/direction would be appreciated. I have no idea what I'm doing wrong. Thanks.
I think the problem is your are calling the function tc.getTestStepByName(String name) with a wrong name, because the newTestStep.toString() doesn't return the Test step name instead it returns the class name (it really returns 'classname' + '#' + 'Integer.toHexString(hashCode())' if it's not override it, see Object.toString()) .
Anyway what you want is to add an assertion for a test step which is just created so add the assertion directly to it instead to find it by name, use:
def assertion = newTestStep.addAssertion("Contains")
instead of:
def assertion = tc.getTestStepByName(newTestStep.toString()).addAssertion("Contains")
The second problem you have is that you're using the assertion incorrectly. The assertion object in your case is an instance of SimpleContainsAssertion and contains() method doesn't exist in this class, to set the string to check in contains assert use setToken() method, I think that you need this to add the two assertions:
def assertion = newTestStep.addAssertion("Contains")
// add token to check
assertion.setToken("Champion5")
// change assert name in order to avoid the popup
// when we create the second one.
assertion.setName("CONTAINS 1")
// create a second assertion
assertion = newTestStep.addAssertion("Contains")
assertion.setToken("Challenger5")
assertion.setName("CONTAINS 2")
instead of :
// add Assertions here
def assertion = tc.getTestStepByName(newTestStep.toString()).addAssertion("Contains")
if (assertion.contains("Champion5")) {
newTestStep.addAssertion("Champion5")
log.info("REST response assertion created into: " + newTestStep)
} else {
log.info("REST response assertion not found in " + newTestStep)
}
if (assertion.contains("Challenger5")) {
newTestStep.addAssertion("Challenger5")
log.info("REST response assertion created into: " + newTestStep)
} else {
log.info("REST response assertion not found in " + newTestStep)
}
This code will result creating this two asserts, one named "CONTAINS 1" and check that response contains the string "Champion5", and a second one named "CONTAINS 2" and check that response contains the string "Challenge5".
Hope this helps,

Resources