Snippets Collections
import com.atlassian.jira.component.ComponentAccessor
import com.onresolve.jira.groovy.user.FieldBehaviours

//copy object in single-select field onto global Numeric field

def formField = getFieldById(getFieldChanged()) // "Estimated Story Points" field
def storyPointsField = getFieldByName("Story Points") // Numeric Field

def estimatedStoryPointsValue = formField.getValue()

if (estimatedStoryPointsValue) {
    try {
        // Convert the selected option into a numeric value
        def numericValue = estimatedStoryPointsValue.toString().toInteger()
        storyPointsField.setFormValue(numericValue)
    } catch (Exception e) {
        storyPointsField.setError("Invalid selection: Unable to convert to a number.")
    }
} else {
    storyPointsField.setFormValue(null) // Clear if no value selected
}
import com.atlassian.jira.component.ComponentAccessor

def allProjects = ComponentAccessor.projectManager

def projects = allProjects.projects

projects.each{ project ->
    log.warn(project.key)
}
// Call the Jira REST API to retrieve all projects
def response = get('/rest/api/3/project')
    .header('Content-Type', 'application/json')
    .asObject(List)

// Check for a successful response
if (response.status != 200) {
    return "Error fetching projects: ${response.status} - ${response.statusText}"
}

// Cast the response body to a List of Maps for static type checking
List<Map> projects = response.body as List<Map>

// Extract project data and map to a simplified structure
return projects.collect { project ->
    [
        id   : project['id'],
        key  : project['key'],
        name : project['name']
    ]
}
import com.atlassian.jira.component.ComponentAccessor

def groupManager = ComponentAccessor.getGroupManager()
def groups = groupManager.getAllGroups()
def sb = []
//Define a string buffer to hold the results

sb.add("<br>Group Name, Active User Count, Inactive User Count, Total User Count")
//Add a header to the buffer
groups.each{ group ->

 def activeUsers = 0
 def inactiveUsers = 0
 Each time we iterate over a new group, the count of active/inactive users gets set back to zero
 def groupMembers = groupManager.getUsersInGroup(group)
 //For each group, fetch the members of the group
    
    groupMembers.each{ member ->
    //Process each member of each group
        
    def memberDetails = ComponentAccessor.getUserManager().getUserByName(member.name)
    //We have to fetch the full user object, using the *name* attribute of the group member
        
        if(memberDetails.isActive()){
            activeUsers += 1 
        }else{
            inactiveUsers += 1
        }
    }//Increment the count of inactive or active users, depending on the current user's status
    
sb.add("<br>"+group.name + ", " + activeUsers + ", " + inactiveUsers+ ", " + (activeUsers + inactiveUsers))
//Add the results to the buffer
}
return sb
//Return the results
import com.atlassian.jira.component.ComponentAccessor

def projectManager = ComponentAccessor.getProjectManager()
def projects = projectManager.getProjectObjects()
def issueManager = ComponentAccessor.getIssueManager()

projects.each{ project ->

  def attachmentsTotal = 0
  def issues = ComponentAccessor.getIssueManager().getIssueIdsForProject(project.id)

  issues.each{ issueID ->

    def issue = ComponentAccessor.getIssueManager().getIssueObject(issueID)
    def attachmentManager = ComponentAccessor.getAttachmentManager().getAttachments(issue).size()
    attachmentsTotal += attachmentManager

  }
  log.warn(project.key + " - " + attachmentsTotal)
}
import java.net.HttpURLConnection
import java.net.URL
import groovy.transform.CompileStatic
import java.util.concurrent.FutureTask

@CompileStatic
def async (Closure close) {
  def task = new FutureTask(close)
  new Thread(task).start()
  return task
} //Tell Groovy to use static type checking, and define a function that we use to create new async requests

String username = "<username>"
String password = "<password>"
//Define the credentials that we'll use to authenticate against the server/DC version of Jira or Confluence
//If we want to authenticate against Jira or Confluence Cloud, we'd need to replace the password with an API token, and replace the username with an email address

// Define a list of URLs to fetch
def urls = [
  "<URL>",
  "<URL>",
  "<URL>",
  "<URL>",
  "<URL>",
]

// Define a list to hold the async requests
def asyncResponses = []

def sb = []
// Loop over the list of URLs and make an async request for each one

urls.each {
  url ->
    //For each URL in the array

    def asyncRequest = {
      //Define a new async request object

      HttpURLConnection connection = null
      //Define a new HTTP URL Connection, but make it null

      try {
        // Create a connection to the URL
        URL u = new URL(url)
        connection = (HttpURLConnection) u.openConnection()
        connection.setRequestMethod("GET")
        //Create a new HTTP connection with the current URL, and set the request method as GET

        connection.setConnectTimeout(5000)
        connection.setReadTimeout(5000)
        //Set the connection parameters

        String authString = "${username}:${password}"
        String authStringEncoded = authString.bytes.encodeBase64().toString()
        connection.setRequestProperty("Authorization", "Basic ${authStringEncoded}")
        //Set the authentication parameters

        // Read the response and log the results
        def responseCode = connection.getResponseCode()
        def responseBody = connection.getInputStream().getText()
        logger.warn("Response status code for ${url}: ${responseCode}")
        sb.add("Response body for ${url}: ${responseBody}")
      } catch (Exception e) {
        // Catch any errors
        logger.warn("Error fetching ${url}: ${e.getMessage()}")
      } finally {
        // Terminate the connection
        if (connection != null) {
          connection.disconnect()
        }
      }
    }
  asyncResponses.add(async (asyncRequest))
}

// Wait for all async responses to complete
asyncResponses.each {
  asyncResponse ->
    asyncResponse.get()
}

return sb
// 1. importing Classes and Packages

import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.project.ProjectManager


def component = ComponentAccessor.getComponent()

// 2. Applying your Import

import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.project.ProjectManager

def projectManager = ComponentAccessor.getComponent(ProjectManager)

// 3. We now have an object that instantiates (is an instance of) the ProjectManager class, and we can move on to exploring its methods.

import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.project.ProjectManager

def projectManager = ComponentAccessor.getComponent(ProjectManager)

return projectManager.getProjectObjects()

/*There’s nothing between the brackets, so we know that it’s not expecting input of any kind. By running this code in the ScriptRunner Console directly, the data returned should be the project keys of every project in your jira instance.*/
// Phone number validator (simple)


getFieldById(getFieldChanged()).getValue().toString().find("[^0-9]|.{11,}") ? getFieldById(getFieldChanged()).setError("This field only allows 10 characters and they must be numeric.") : getFieldById(getFieldChanged()).clearError();
// Select Current or future date


new Date().parse("E MMM dd H:m:s z yyyy", getFieldById(getFieldChanged()).getValue().toString()) - new Date() < 0 ? getFieldById(getFieldChanged()).setError('Please select a future or current date') : getFieldById(getFieldChanged()).clearError();
//Max value 10 characters 


getFieldById(getFieldChanged()).getValue().toString().find("[^0-9,\\.]|[0-9]{11,}|[0-9,\\.]{12,}|.*\\.[0-9]{3,}") ? getFieldById(getFieldChanged()).setError('Only numeric characters allowed, maximum to 10 including 2 decimal places') : getFieldById(getFieldChanged()).clearError();
//Allow 1 digit from 0 to 5



getFieldById(getFieldChanged()).getValue().toString().find("([^0-5]|{1})") ? getFieldById(getFieldChanged()).setError('Only numeric characters allowed 1 to 5') : getFieldById(getFieldChanged()).clearError();
//File: src/JiraStuff/groovy/M/ToBePaid_ValidateMaxLengthNumeric.groovy
//Field: % to be Paid - customfield_10530
//Description: Validate max length and numeric


String strVal = getFieldById(getFieldChanged()).getValue().toString()
if( strVal.length() > 0 ) {
  strVal.find("[^0-9]|.{4,}") || strVal.toInteger() > 100 ? getFieldById(getFieldChanged()).setError('This field only allows 3 numeric characters and no more than 100') : getFieldById(getFieldChanged()).clearError();
} else {
    getFieldById(getFieldChanged()).clearError();
}
// restrict editing only to authorized users

import com.onresolve.jira.groovy.user.FieldBehaviours
import com.atlassian.jira.component.ComponentAccessor
import groovy.transform.BaseScript

// Set the base script annotation for field behaviours
@BaseScript FieldBehaviours fieldBehaviours

// Get the custom field by name
def customField = getFieldByName("My Field")

// Retrieve the username of the currently logged-in user
def username = ComponentAccessor.getJiraAuthenticationContext().getLoggedInUser().getUsername()

// Define an array of authorized usernames
def authorizedUsernames = ["Service_Account", "belle_jar"]

// Check if the current user is one of the authorized users
if (!authorizedUsernames.contains(username)) {
    // If the user is not in the list, make the field read-only
    customField.setReadOnly(false)
} else {
    // If the user is in the list, allow editing
    customField.setReadOnly(true)
}
// restrict editing only to authorized users

import com.onresolve.jira.groovy.user.FieldBehaviours
import com.atlassian.jira.component.ComponentAccessor
import groovy.transform.BaseScript

// Set the base script annotation for field behaviours
@BaseScript FieldBehaviours fieldBehaviours

// Get the custom field by name
def customField = getFieldByName("My Field")

// Retrieve the username of the currently logged-in user
def username = ComponentAccessor.getJiraAuthenticationContext().getLoggedInUser().getUsername()

// Define an array of authorized usernames
def authorizedUsernames = ["Service_Account", "belle_jar"]

// Check if the current user is one of the authorized users
if (!authorizedUsernames.contains(username)) {
    // If the user is not in the list, make the field read-only
    customField.setReadOnly(false)
} else {
    // If the user is in the list, allow editing
    customField.setReadOnly(true)
}
// customfield Security Level

import com.onresolve.jira.groovy.user.FieldBehaviours
import groovy.transform.BaseScript

@BaseScript FieldBehaviours fieldBehaviours

// Get the field by its name
def securityLevelField = getFieldByName("Security Level")

// Make the field read-only
securityLevelField.setReadOnly(true)
// customfield System Subtype

import com.onresolve.jira.groovy.user.FieldBehaviours
import groovy.transform.BaseScript
import static com.atlassian.jira.issue.IssueFieldConstants.*
import com.atlassian.jira.component.ComponentAccessor

@BaseScript FieldBehaviours fieldBehaviours

def systemSubtypeField = getFieldByName("System Subtype")
def customFieldManager = ComponentAccessor.getCustomFieldManager()
def optionsManager = ComponentAccessor.getOptionsManager()

def customField = customFieldManager.getCustomFieldObjectByName("System Subtype")
def config = customField.getRelevantConfig(getIssueContext())
def options = optionsManager.getOptions(config)

// Filter options
def allowedValues = ["Application Function", "Component", "Microservice", "Module", "NUDD", "Tool", "None"]
def filteredOptions = options.findAll {
    it.value in allowedValues
}

systemSubtypeField.setFieldOptions(filteredOptions)
// Service Form PS

import com.onresolve.jira.groovy.user.FieldBehaviours
import com.onresolve.jira.groovy.user.FormField

// Get the specific field
FormField myField = getFieldById("customfield_xxxx") // Vendor Dev Status

// Set the tooltip description with AUI icon styling
myField.setLabel("System Sales Catalog Product Code <span class='aui-icon aui-icon-small aui-iconfont-info' title='Use this field to indicate the product code associated with the system, as stated in the Sales Catalog for this system' style='cursor: help; margin-left: 5px;'></span>")


URL internalURL = new URL(url)
return internalURL.openConnection().inputStream.withCloseable {
  it.bytes.encodeBase64();
}
...
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    // AndroidX libraries
    implementation 'androidx.core:core-ktx:1.9.0'
    implementation 'androidx.appcompat:appcompat:1.5.1'
    implementation 'androidx.cardview:cardview:1.0.0'
    implementation 'com.google.android.material:material:1.7.0'
    implementation 'androidx.gridlayout:gridlayout:1.0.0'
    implementation 'androidx.leanback:leanback:1.1.0-rc02'
    implementation 'androidx.mediarouter:mediarouter:1.3.1'
    implementation 'androidx.palette:palette-ktx:1.0.0'
    implementation 'androidx.recyclerview:recyclerview:1.2.1'
    implementation 'androidx.annotation:annotation:1.5.0'

    // Note: these libraries require that the Google repository has been declared
    // in the pluginManagement section of the top-level build.gradle file.
}
  pluginManagement {
      repositories {
          google()
          mavenCentral()
          gradlePluginPortal()
      }
  }
  dependencyResolutionManagement {
      repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
      repositories {
          google()
          mavenCentral()
      }
  }
  rootProject.name = "Test App"
  include ':app'
  
android {
  ...
  defaultConfig {
    ...
    minSdkVersion 26
    targetSdkVersion 29
  }
}
stage ('ANOTHER JOB'){
            steps {
                build job: "Release Helpers/(TEST) Schedule Release Job2",
                parameters: [
                    [$class: 'StringParameterValue', name: 'V', value: "${newRelease}"],
                    [$class: 'StringParameterValue', name: 'ReleaseDate', value: "${currentRelease}"]
                ]
            }
        }
pipeline {
    stages { ... }
    post {
       // only triggered when blue or green sign
       success {
           slackSend(channel: 'alerts-testing', color: 'good', message: ":party_parrot: NOTIFICATION: NEW RELEASE ${newRelease} WILL BE CREATED AUTOMATICALLY :party_parrot:")
       }
       // triggered when red sign
       failure {
           slackSend(channel: 'alerts-testing', color: 'RED', message: ":alarm_clock: NOTIFICATION: NEW RELEASE ${newRelease} WITH SOME FAILURE :alarm_clock:")
       }
       // trigger every-works
       always {
           slackSend ...
       }
    }
}
        newRelease = listLastReleaseTag(service[0])
        newRelease = "V${listLastReleaseTag(service[0])}"
pipeline {
    agent { label 'spot-instance' }
    
        stage('Print') {
            steps {
                script {
                    def now = new Date()
                    dateRelease = now.format("yyyy-MM-dd", TimeZone.getTimeZone('UTC'))
                    echo "Current date ${dateRelease}."
                }
            }
        }

        stage ('Run another Job'){
            steps {
                build job: "Release Helpers/(TEST) Schedule Release Job2",
                parameters: [
                    [$class: 'StringParameterValue', name: 'V', value: "${dateRelease}"]

                ]
            }
        }
}
pipeline {
    agent { label 'spot-instance' }
    
    environment {
        currentDate = sh(returnStdout: true, script: 'date +%Y-%m-%d').trim()
    }

        stage ('Run another Job'){
            steps {
                build job: "Release Helpers/(TEST) Schedule Release Job2",
                parameters: [
                    [$class: 'StringParameterValue', name: 'ReleaseDate', value: "${currentDate}"]

                ]
            }
        }
}

star

Tue Feb 11 2025 13:44:50 GMT+0000 (Coordinated Universal Time)

#groovy
star

Fri Nov 15 2024 20:38:46 GMT+0000 (Coordinated Universal Time)

#groovy
star

Fri Nov 15 2024 20:18:16 GMT+0000 (Coordinated Universal Time)

#groovy
star

Thu Nov 14 2024 13:27:34 GMT+0000 (Coordinated Universal Time)

#groovy
star

Thu Nov 14 2024 13:22:52 GMT+0000 (Coordinated Universal Time)

#groovy
star

Thu Nov 14 2024 13:17:39 GMT+0000 (Coordinated Universal Time)

#groovy
star

Wed Nov 13 2024 20:54:01 GMT+0000 (Coordinated Universal Time) https://docs.atlassian.com/software/jira/docs/api/9.6.0/com/atlassian/jira/project/ProjectManager.html

#groovy
star

Wed Nov 13 2024 19:51:55 GMT+0000 (Coordinated Universal Time)

#groovy
star

Wed Nov 13 2024 19:49:37 GMT+0000 (Coordinated Universal Time)

#groovy
star

Wed Nov 13 2024 19:47:43 GMT+0000 (Coordinated Universal Time)

#groovy
star

Wed Nov 13 2024 19:45:14 GMT+0000 (Coordinated Universal Time)

#groovy
star

Wed Nov 13 2024 19:38:27 GMT+0000 (Coordinated Universal Time)

#groovy
star

Wed Nov 13 2024 18:07:15 GMT+0000 (Coordinated Universal Time)

#groovy
star

Wed Nov 13 2024 18:07:11 GMT+0000 (Coordinated Universal Time)

#groovy
star

Wed Nov 13 2024 18:03:55 GMT+0000 (Coordinated Universal Time)

#groovy
star

Wed Nov 13 2024 18:01:50 GMT+0000 (Coordinated Universal Time)

#groovy
star

Wed Nov 13 2024 17:50:24 GMT+0000 (Coordinated Universal Time)

#groovy #javascript
star

Wed Feb 01 2023 10:33:28 GMT+0000 (Coordinated Universal Time)

#groovy #base64
star

Sat Dec 31 2022 10:56:22 GMT+0000 (Coordinated Universal Time) https://developer.android.com/studio/intro/migrate

#groovy
star

Sat Dec 31 2022 10:56:11 GMT+0000 (Coordinated Universal Time) https://developer.android.com/studio/intro/migrate

#groovy
star

Tue Mar 01 2022 13:29:49 GMT+0000 (Coordinated Universal Time) https://developer.android.com/guide/components/fundamentals.html#Components

#groovy
star

Mon Aug 09 2021 10:33:23 GMT+0000 (Coordinated Universal Time)

#variable #groovy #jenkins #pipeline
star

Thu Aug 05 2021 11:19:16 GMT+0000 (Coordinated Universal Time)

#variable #groovy #jenkins #pipeline #currentdate
star

Thu Aug 05 2021 11:17:02 GMT+0000 (Coordinated Universal Time)

#variable #groovy #jenkins #pipeline

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension