All of the documentation I've found on ScriptRunner and creating pages in Confluence assumes you are doing it from Jira, so it adds unnecessary steps to authenticate. I want to run the script in Confluence with no input from Jira or outside system.
Here is the code I had so far that gets hung up on the authenticatedRequestFactory:
import com.atlassian.applinks.api.ApplicationLink
import com.atlassian.applinks.api.ApplicationLinkService
import com.atlassian.applinks.api.application.confluence.ConfluenceApplicationType
import com.atlassian.sal.api.component.ComponentLocator
import com.atlassian.sal.api.net.Request
import com.atlassian.sal.api.net.Response
import com.atlassian.sal.api.net.ResponseException
import com.atlassian.sal.api.net.ResponseHandler
import groovy.json.JsonBuilder
import groovy.json.JsonSlurper
def confluenceLink = getPrimaryConfluenceLink()
assert confluenceLink // must have a working app link set up
def authenticatedRequestFactory = confluenceLink.createImpersonatingAuthenticatedRequestFactory()
// set the page title - this should be unique in the space or page creation will fail
def pageTitle = "Teset Discussion"
def pageBody = """h3. Test
{quote}This is a quote{quote}
Yada yada, use this page to discuss the above...
"""
def params = [
type: "page",
title: pageTitle,
space: [
key: "COM" // set the space key - or calculate it from the project or something
],
/* // if you want to specify create the page under another, do it like this:
ancestors: [
[
type: "page",
id: "14123220",
]
],*/
body: [
storage: [
value: pageBody,
representation: "wiki"
],
],
]
authenticatedRequestFactory
.createRequest(Request.MethodType.POST, "rest/api/content")
.addHeader("Content-Type", "application/json")
.setRequestBody(new JsonBuilder(params).toString())
.execute(new ResponseHandler<Response>() {
#Override
void handle(Response response) throws ResponseException {
if(response.statusCode != HttpURLConnection.HTTP_OK) {
throw new Exception(response.getResponseBodyAsString())
}
else {
def webUrl = new JsonSlurper().parseText(response.responseBodyAsString)["_links"]["webui"]
}
}
})
The above sample is a trimmed down version from this documentation: https://scriptrunner.adaptavist.com/latest/jira/interacting-with-confluence-from-jira.html Appreciate any direction on how to just create a page.
Example code was shared on the following Atlassian thread: https://community.developer.atlassian.com/t/how-to-create-a-confluence-page-with-scriptrunner-via-rest-api/23695 It reviews how to create a page in Confluence without having to be connected to Jira.
Related
I'm trying to add a new screen to Subiquity but Subiquity gets stuck every time I run it.
running server pid 40812
connecting... /
To create my controller I used an example from DESIGN.md
My server controller class is as below:
import logging
from subiquity.common.apidef import API
from subiquity.server.controller import SubiquityController
log = logging.getLogger('subiquity.server.controllers.example')
class ExampleController(SubiquityController):
endpoint = API.example
model_name = 'example'
async def GET(self) -> str:
return self.model.thing
async def POST(self, data: str):
self.model.thing = data
await self.configured()
Also, I added my Example controller class to controllers[] in subiquity/server/server.py:
controllers = [
# other classes
"Kernel",
"Keyboard",
"Example",
"Zdev",
"Source",
# some other classes
]
And added example = simple_endpoint(str) to apidef.py
My model as simple as possible:
class ExampleModel:
thing = "example_var"
What might cause the problem? If I remove my Example controller from controllers[], Subiquity works but obviously doesn't use my controller.
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)
I use wp job manager on my website. when I tried to add listing by xmlrpc, everything is fine, but Categories and Location are empty.
Screenshot
Screenshot
My code is as below. Could you tell me what's wrong with my code?
Thanks
from wordpress_xmlrpc import Client, WordPressPost
from wordpress_xmlrpc.methods.posts import GetPosts
from wordpress_xmlrpc.methods import posts
from wordpress_xmlrpc import WordPressTerm
from wordpress_xmlrpc.methods import taxonomies
wp = Client('http://127.0.0.1/15wp/xmlrpc.php', 'admin', '123456')
# now let's create a new product
widget = WordPressPost()
widget.post_type = 'job_listing'
widget.title = 'Widgetlast02'
widget.content = 'This is the widgets description.'
widget.post_status = 'publish'
widget.custom_fields = []
widget.custom_fields.append({
'job_location': 'Newyork',
'job_listing_category': 'hotel'
})
widget.id = wp.call(posts.NewPost(widget))
The custom_fields attribute expects a list of dicts.
Within each dict, it expects values for key and value fields.
Here, key is the name of the custom field, and value is the value you want to assign to it.
Below is the snippet for your specific example.
widget.custom_fields = [
{
'key': 'job_location',
'value': 'Newyork'
},
{
'key': 'job_listing_category',
'value': 'hotel'
}
]
This is just a guess from looking at the documentation for WordPressPost in wordpress_xmlrpc:
(Emphasis mine)
class WordPressPost
Represents a post, page, or other registered custom post type in
WordPress.
id
user
date (datetime)
date_modified (datetime)
slug
post_status
title
content
excerpt
link
comment_status
ping_status
terms (list of WordPressTerms)
terms_names (dict)
custom_fields (dict)
enclosure (dict)
password
post_format
thumbnail
sticky
post_type
It expects custom_fields to be a dict - you're creating a list and then inserting a dict into that list:
widget.custom_fields = []
widget.custom_fields.append({
'job_location': 'Newyork',
'job_listing_category': 'hotel'
})
This will probably work better:
widget.custom_fields = {
'job_location': 'Newyork',
'job_listing_category': 'hotel'
}
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
Can we request a https link using HttpBuilder ?
1 - if yes then is their any specific parameters or properties we need to set while request the data.
2 - if not then can we request same as the normal http link as in the below e.g.
def http = new HTTPBuilder('http://some_link');
def resp = http.get(path: '/abcd/efg', query:[login:'login_id', pass: 'password',ttype:'trans_type',prodid:'prod_id'], contentType : XML, headers : [Accept : 'application/xml'] )
Just tried it, and it does work as it says in the docs...
#Grab( 'org.ccil.cowan.tagsoup:tagsoup:1.2' )
#Grab( 'org.codehaus.groovy.modules.http-builder:http-builder:0.5.2' )
import org.ccil.cowan.tagsoup.Parser
import groovyx.net.http.HTTPBuilder
import static groovyx.net.http.ContentType.*
// Using an https url
new HTTPBuilder( 'https://twitter.com' ).with {
// Get from the given path as TEXT
get( path:'/tim_yates', contentType:TEXT ) { resp, reader ->
// Pass the html through tagsoup and generate a parser
new XmlParser( new Parser() ).parseText( reader.text ).with {
// print the title text from inside the head section
println head.title.text()
}
}
}