This script takes a list of custom field names, and searches each issue in the instance for places where that custom field has been used (i.e., where it has a value other than null).

In this way, we gain insight into the usage of custom fields within a Jira Cloud instance.

The script is interesting for a number of reasons. First, it’s another instance of us having to parse a rawBody response before we can make use of it. Second, it handles the need for pagination, which we’ve also talked about in recent posts.

My intent for this script is for it to serve as a basis for future custom field work in Jira Cloud. Namely, I’d like to be able to easily rename any field with “migrated” in the title.

 

 import groovy.json.JsonSlurper
 
def stillPaginating = true
//Loop to paginate
 
def startAt = 0
//Start at a pagination value of 0
 
def maxResults = 50
//Increment pagination by 50
 
def issueIDs = []
def fieldNames = ["Actual end", "Actual start", "Change risk", "Epic Status"]
def customFieldMap = [: ]
 
 
//Get all the fields in the system
def fieldIDs = get("/rest/api/3/field")
  .header('Content-Type', 'application/json')
  .header('Accept', 'application/json')
  .asBinary()
 
def inputStream = fieldIDs.rawBody

Get All Filters in a Jira System

Here’s the truth: getting all of the filters in a Jira DC instance with ScriptRunner is awkward and fussy.  There’s no method that simply returns all of the filters. 

Instead, we need to first return all of the users in the system.  And then we need to examine all of the filters that each of them owns, as each filter must have an owner.  Here’s an example of some code that does that:

 import com.atlassian.jira.user.ApplicationUser
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.bc.filter.SearchRequestService
import com.atlassian.jira.issue.search.SearchRequest
import com.atlassian.jira.bc.user.search.UserSearchParams
import com.atlassian.jira.bc.user.search.UserSearchService
   
   
SearchRequestService searchRequestService = ComponentAccessor.getComponent(SearchRequestService.class)
UserSearchService userSearchService = ComponentAccessor.getComponent(UserSearchService)
def sb = new StringBuffer()
   
UserSearchParams userSearchParams = new UserSearchParams.Builder()
    .allowEmptyQuery(true)
    .includeInactive(false)
    .ignorePermissionCheck(true)
    .build()
//Define the parameters of the query
  
//Iterate over each user's filters
userSearchService.findUsers("", userSearchParams).each{ApplicationUser filter_owner ->
    try {
        searchRequestService.getOwnedFilters(filter_owner).each{SearchRequest filter->
            String jql = filter.getQuery().toString()
            //for each fiilter, get JQL and check if it contains our string
             
                sb.append("Found: ${filter.name}, ${jql}\n" + "<br>")
             
        }
    } catch (Exception e) {
            //if filter is private
           sb.append("Unable to get filters for ${filter_owner.displayName} due to ${e}")
    }
}
 
return sb 

 

Getting a list of filters on Jira Cloud is much simpler, as there’s a REST API that accomplishes this.  If we

Confluence Meta-Macros and the joy of being organized

Let’s talk about meta-macros.  That is, macros that examine other macros.   I just made up the term, so don’t be concerned if you can’t find other examples on the internet.

If you wanted some insight into which pages in your Confluence Instance were using a specific macro, how would you find that information?

You could certainly check each page manually, but that sounds dreadful.

One option to get Macro information is this ScriptRunner script that I wrote, which examines the latest version of each page in each Space for references to the specified macro:

 import com.atlassian.sal.api.component.ComponentLocator
import com.atlassian.confluence.spaces.SpaceManager
import com.atlassian.confluence.pages.PageManager
import com.atlassian.confluence.pages.Page
def pageManager = ComponentLocator.getComponent(PageManager)
def spaceManager = ComponentLocator.getComponent(SpaceManager)
def spaces = spaceManager.getAllSpaces()
  
def macroRef = 'ac:name="info"'
  
spaces.each {
  spaceObj ->
    def pages = pageManager.getPages(spaceObj, false)
  pages.each {
    page ->
      if (page.getBodyContent().properties.toString().contains(macroRef) && page.version == page.latestVersion.version) {
        log.warn("'${page.title}' (version ${page.version}) is the latest version of the page, and contains the target macro")
      }
  }
}
 

 

But what if you wanted MORE information?  What if you wanted to know every macro running on every page in the system, and you didn’t have ScriptRunner to do it for you?  In that

Overview

I spoke to someone recently on the subject of learning to use ScriptRunner and Groovy.  One of the questions he had was around the number of results that were returned when he called the API.  That is, he had set maxResults to 500, but only 100 results were returned.   Why?
It’s true that you have some agency over the number of results that are returned by the Jira (and Confluence) REST API.  You can set the maxResults value as part of the request, and receive more than the 50 items that are returned by default.   However, there are limits to this parameter.  The API has a built-in limit, and no matter what you set maxResults to, you cannot exceed that limit.

Let’s look at an example.

If I call /rest/api/3/search?jql=project is not EMPTY, it’ll return every issue in the instance from a project that isn’t empty.  That’s potentially a lot of issues. 
However if we look at the results that are returned, there are some meta attributes in addition to the issues themselves.  In our example, the JSON that is returned starts with this:
 {
"expand": "schema,names",
"startAt": 0,
"maxResults": 50,
"total": 35,
 
From this, we see that

This script searches for Jira filters by name, then by filter ID, and then updates the permissions set applied to them.

It’s useful for updating a bulk list of filter names, but really it’s an exercise in working with filters and the search service.

The script iterates through an array of filter names. For each filter name, it uses the searchRequestManager to find that filter object.  It then uses the filter ID of the object to return a filter object.  This seems redundant, but the object returned by the searchRequestManager isn’t actually a filter. It’s information about the filter. 

When we search for the filter by name using searchRequestManager , it will return any filter that has that name. For that reason, we must treat the results like an array, and iterate through them.  For each filter ID that is returned by the name search, we use the searchRequestManager to search for the filter object.

Once we’ve got a filter object, we apply the new permissions to it and commit the change with updateFilter().

 

 

 import com.atlassian.jira.bc.JiraServiceContextImpl
import com.atlassian.jira.bc.filter.SearchRequestService
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.sharing.SharePermissionImpl
import com.atlassian.jira.sharing.SharedEntity
import com.atlassian.jira.sharing.type.ShareType
import com.atlassian.jira.issue.search.*

def searchRequestService = ComponentAccessor.getComponent(SearchRequestService)
def currentUser = ComponentAccessor.jiraAuthenticationContext.loggedInUser
def searchRequestManager 

Introduction

Well, it finally happened.  I finally had to start learning JavaScript.

It’s actually not that bad, I probably should have learned a while ago.  My use case for it is writing Confluence Macros and plugins for both Confluence and Jira. I started with the plugins, for simplicity’s sake.  
My inspiration came from a post on the Atlassian Community Forums. Someone had requested a way to essentially mirror the setup of a macro. But they wanted to mirror the most recent child page, of a parent page.
I think that without pretty strong knowledge of Confluence and the REST API, I’d have struggled to complete this.  It enough work to learn JavaScript’s basic tenets as I went.

 

Digging Into The Problem

Okay so what do we actually need the script to do? We need it to:

  •  Figure out the most recently updated child page of a parent page
  •  Fetch the macro setup of the child page
  • Update the parent page accordingly

These are the three high-level functions that the macro needs to accomplish. 

Figuring out the most recently updated child page wasn’t hard.  You can make a call to baseURL + pageID + “/child/page?limit=1000&expand=history.lastUpdated. This returns a list

As is often the case, the point of this blog isn’t so much to explain how to do something complicated. The point is that I’m trying to explain something simple that should be easy to find an answer for, but was not. In this case my question was “what on earth is a UserTemplate (User Template) in Confluence”?

On the surface, it seems like creating a new user in Confluence should be a pretty straightforward process.   There’s a UserAccessor class, and that class has a createUser() method.   However, the expected inputs to that method are a User Template object and a Credentials object. From the class documentation:

  • createUser

     ConfluenceUser createUser(com.atlassian.user.User userTemplate,
                              com.atlassian.user.security.password.Credential password)

The import required to work with Credential is spelled out for us, but the userTemplate is a different story.   There’s virtually no documentation on what that means, and no amount of Googling “Confluence User Template”, “UserTemplate”, “Confluence Create User Template” will actually tell you what to do. Part of the issue is that “template” means several different things in the context of Confluence, so that muddies the waters.

Let’s cut to the chase. Here’s the code that I eventually came up with:

 import com.atlassian.confluence.api.model.people.User
import com.atlassian.sal.api.component.ComponentLocator
import 

Introduction

In a bid to contribute more to the Atlassian Community, I took a look at the most recent requests and questions on the Forums.  One that caught my eye was a request for a Confluence Macro that would:

“…display on the restricted page exactly who has access (including a breakout of all group members, not just the group name) to create transparency and build confidence in the selected user group that they are posting in the appropriately restricted area.”

I’d never created a Confluence Macro before, and this seemed like a challenge I could meet.

Please note that this isn’t a how-to on creating Macros, but really just an accounting of my experience learning the tool.

Getting Started

The first thing I did was check to see what Atlassian has to say on the subject. Confluence Macros are written in Apache Velocity, which is quite different from the Groovy that I’m used to working with.

All of the functional lines in Velocity start with a #, which makes a Velocity script look like one big page of commented-out code.  The truth is that Velocity is very old and pretty clunky.  The last news update to the project was

This script returns a list of pages in a Confluence instance that use a specified macro.

There are a number of references to “MacroManager” in the Confluence API documentation, but none of the implementations seemed to work for me.

For that reason, our best bet for checking on Macro usage is to examine the body content of each page, and look for a specific reference to the macro in question.

We also need to check that the page in question is the latest version of the page. Otherwise the script checks all versions of all pages.

 

 import com.atlassian.sal.api.component.ComponentLocator
import com.atlassian.confluence.spaces.SpaceManager
import com.atlassian.confluence.pages.PageManager
import com.atlassian.confluence.pages.Page
def pageManager = ComponentLocator.getComponent(PageManager)
def spaceManager = ComponentLocator.getComponent(SpaceManager)
def spaces = spaceManager.getAllSpaces()
  
def macroRef = 'ac:name="info"'
//Replace "info" with the name of the macro you want to assess
  
spaces.each{  spaceObj ->
//Get all Spaces in the instance
  def pages = pageManager.getPages(spaceObj, false)
  pages.each{    page ->
//Get all pages in the instances
      if (page.getBodyContent().properties.toString().contains(macroRef) && page.version == page.latestVersion.version) {
      //Check if the page contains the macro, then check to see if it's the most current version of the page
        log.warn("'${page.title}' (version ${page.version}) is the latest version of the page, and contains the target macro")
      }