Scriptrunner Create issue and assign to existing epic - groovy

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

Related

HTTPSConnectionPool(host='api.razorpay.com', port=443): Max retries exceeded with url: /v1/orders

I was developing a social-media/eCommerce web app with Django. I want to add a payment gateway for purchasing products on the website for that I am using 'Razorpay'.
I integrated it which worked fine with my app. But I wanted to store the transaction-related details in a model called 'TransactionDetails'. For that, I call a new function within the view that handles the Razorpay gateway. which creates the instance of the model and saves it.
But for some reason when I call that function I am getting this error, please help me to understand what is happening.
here's my view :
from django.shortcuts import render, redirect
import razorpay
from django.views.decorators.csrf import csrf_exempt
from weShare.settings import razorpay_id, razorpay_secret_key
from django.contrib.auth.mixins import UserPassesTestMixin, LoginRequiredMixin
from django.urls import reverse_lazy
from social.models import *
from social.forms import *
from .models import TransactionDetails
from social.models import UserProfile
client = razorpay.Client(auth=(razorpay_id, razorpay_secret_key))
def home(request, pk):
rentee = UserProfile.objects.get(user=request.user)
renteeName = rentee.user
renteeLocation = rentee.location
post = Post.objects.get(pk=pk)
renter = post.author
product = post.productName
subPeriod = post.subscriptionPeriod
montlycharge = post.productMonthlyCharge
loc = rentee.location
order_amount = post.deposite*100
order_currency = 'INR'
order_receipt = 'order_rcptid_11'
notes = {'Shipping address': 'Bommanahalli, Bangalore'} # OPTIONAL
payment_order = client.order.create(dict(amount=order_amount, currency=order_currency, payment_capture=1))
payment_order_id = payment_order['id']
createTransaction(request, rentee, pk, payment_order_id) # here
context ={
'amount' : 100,
'razorpay_id' : razorpay_id,
'order_id' : payment_order_id,
'razorpay_secret_key' : razorpay_secret_key,
'renter' : renter,
'product' : product,
'subPeriod' : subPeriod,
'montlycharge' : montlycharge,
'order_amount' : order_amount/100,
}
return render(request, 'paymentgateway/index.html', context)
def createTransaction(request, rentee, pk, payment_order_id):
post = Post.objects.get(pk=pk)
renter = post.author
product = post.productName
subPeriod = post.subscriptionPeriod
montlycharge = post.productMonthlyCharge
loc = rentee.location
order_amount = post.deposite*100
#Inserting data in TrasactionDetails object
transaction = TransactionDetails(rentee=request.user, product=product, renter=renter, subPeriod=subPeriod, monthlyCharge=montlycharge, deposite=order_amount, address=loc, order_id=payment_order_id)
transaction.save()
Here's the model.py :
from django.db import models
from social.models import *
from django.contrib.auth.models import User
# Create your models here.
class TransactionDetails(models.Model):
rentee = models.ForeignKey(User, on_delete=models.CASCADE)
product = models.CharField(max_length=200, default="")
renter = models.CharField(max_length=200, default="")
subPeriod = models.IntegerField(default=3)
monthlyCharge = models.IntegerField(default=100)
deposite = models.IntegerField()
address = models.CharField(max_length=300)
order_id = models.CharField(max_length=100, default="failed")
def __str__(self):
return '%s %s'%(self.product, self.renter)
This error is because of your internet connection. Check your internet connection. We are calling razorpay api so we need internet connection. I got this same error when my internet connection gone but when my internet back it working as normal.

Scriptrunner/ Copying Project while logged-in as another user

I want to use my script, so that it will be executed by someone who is not me, but another user (ServiceUser) in the Jira Instance.
This is my functioning code, but I do not know how to make someone else execute it.
import com.atlassian.jira.project.Project
import com.atlassian.jira.project.ProjectManager
import com.atlassian.jira.project.AssigneeTypes
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.user.ApplicationUser
import com.atlassian.jira.component.ComponentAccessor
import com.onresolve.scriptrunner.canned.jira.admin.CopyProject
import org.apache.log4j.Logger
import com.atlassian.jira.bc.projectroles.ProjectRoleService
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.security.roles.ProjectRole
import com.atlassian.jira.util.SimpleErrorCollection
import com.atlassian.jira.security.roles.ProjectRoleManager
import com.atlassian.jira.project.ProjectManager
import com.atlassian.jira.project.Project
import com.atlassian.jira.security.roles.ProjectRoleActor
import com.atlassian.jira.bc.project.ProjectCreationData
import com.atlassian.jira.bc.project.ProjectService
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.project.AssigneeTypes
import com.atlassian.jira.project.type.ProjectTypeKey
// the key for the new project
def projectKey = "EXA987"
def projectName = "EXA987"
def log = Logger.getLogger("com.onresolve.jira.groovy.MyScript")
Thread executorThread = new Thread(new Runnable() {
void run() {
def copyProject = new CopyProject()
def inputs = [
(CopyProject.FIELD_SOURCE_PROJECT) : "SWTEMP",
(CopyProject.FIELD_TARGET_PROJECT) : projectKey,
(CopyProject.FIELD_TARGET_PROJECT_NAME) : projectName,
(CopyProject.FIELD_COPY_VERSIONS) : false,
(CopyProject.FIELD_COPY_COMPONENTS) : false,
(CopyProject.FIELD_COPY_ISSUES) : false,
(CopyProject.FIELD_COPY_DASH_AND_FILTERS) : false,
]
def errorCollection = copyProject.doValidate(inputs, false)
if(errorCollection.hasAnyErrors()) {
log.warn("Couldn't create project: $errorCollection")
}
else {
def util = ComponentAccessor.getUserUtil()
def adminsGroup = util.getGroupObject("jira-administrators")
assert adminsGroup // must have jira-administrators group defined
def admins = util.getAllUsersInGroups([adminsGroup])
assert admins // must have at least one admin
ComponentAccessor.getJiraAuthenticationContext().setLoggedInUser(util.getUserByName(admins.first().name))
copyProject.doScript(inputs)
}
}
})
executorThread.start()
I stumbled upon other codes, using things like
def oldLoggedInUser = jiraAuthenticationContext.getLoggedInUser()
jiraAuthenticationContext.setLoggedInUser(serviceUser)
jiraAuthenticationContext.setLoggedInUser(oldLoggedInUser)
but it was not succesful for me.
I have used following solution to change user during script execution:
def authContext = ComponentAccessor.getJiraAuthenticationContext();
def currentUser = authContext.getLoggedInUser();
def superuser=ComponentAccessor.getUserManager().getUserByKey("ANOTHER_USER_ACCOUNT")
authContext.setLoggedInUser(superuser);
// < do the needed work>
authContext.setLoggedInUser(currentUser);
I had first issues as my used another account had not needed Jira access rights (and I got funny "user must be logged in" errors)

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

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;

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

Resources