Code Snippets

3 minute readReferenceExtensibilityDeveloper productivity


This chapter is provided to share some code snippets that show the usage of the groovy libraries.

Auto-Generated Code

After generation of the plugin using pdk you will see that you have a template of a plugin class which inherits FlowPlugin. This file will be at dsl/properties/groovy/lib/YOURCLASS.groovy.

For each procedure in the plugin, a corresponding method will be created in a file with the same name as the procedure. For example, dsl/procedures/YOUR_PROCEDURE/steps/YOUR_PROCEDURE.groovy will look something like this:

$[/myProject/groovy/lib/scripts/preamble.groovy.ignore] YOURCLASS plugin = new YOURCLASS() plugin.runStep('YOURPROCEDURE', 'YOURPROCEDURESTEP', 'functionName');

The main plugin class will have a function called functionName with some template code:

def functionName(StepParameters runtimeParameters, StepResult sr) { ...; }

Retrieving parameter values from configuration and step

Using one API

Here is a snippet where in both config as well as step parameter values can be retrieved using a single StepParameters object.

def runtimeParameters = context.getRuntimeParameters().getAsMap(); // runtimeParameters is a Map with following fields: // user, password, proxy_user, proxy_password, basic_user, basic_password (taken from config) // requestMethod and requestContent (taken from procedure parameters). println runtimeParameters['requestMethod'] println runtimeParameters['proxy_user']

Using two different APIs

Here is a snippet where in config and step parameter values are retrieved using different APIs.

Context context = this.newContext() StepParameters parameters = context->getStepParameters() def cred = parameters.getParameter('credential') def url = parameters.getParameter('url').getValue() def method = null if (parameters.isParameterExists('method')) { def parameter = parameters.getParameter('method') method = parameter.getValue() } def username = null def password = null if (cred != null) { username = cred.getUserName() password = cred.getSecretValue() }
Config configValues = context.getConfigValues()

You can then use the methods in Config object to access the config values.

Setting step results

for (int i : 1..100){ stepResult.setJobStepSummary("Progress: $i\n") stepResult.applyAndFlush() Thread.sleep(1000) }


// Step 1. Creating new stepResult object. StepResult stepResult = context.newStepResult() // Step 2. Adding action items. stepResult.setOutputParameter('executionResult', 'Successfully finished!') stepResult.setJobStepSummary('Done with success') // Step 3. Applying changes. stepResult.apply()

Performing REST requests

// Retrieving new rest client object to use the 'endpoint' value from the configuration (and authorization too). REST restClient = context.newRESTClient() // creating HTTP::Request object using our wrappers HTTPRequest req = restClient.newRequest([method: 'GET', path: '/api/v2/query', query: [ id: '2']]) // Performing request and getting a response object def response = restClient.doRequest(req) // Printing response content: println(response.toString())

CLI execution

// Step 1. Importing the Component Manager and the CLI class (place at the top of a file) import com.cloudbees.flowpdf.components.ComponentManager import com.cloudbees.flowpdf.components.cli.* // Step 2. Loading component and creating CLI executor with working directory of current workspace. (in the step method) CLI cli = (CLI) ComponentManager.loadComponent(CLI.class, [ workingDirectory : System.getenv("COMMANDER_WORKSPACE") ]) // Step 3. Creating new command with ls as shell and -la as parameter. Command command = cli.newCommand('ls', ['-la']) // adding two more parameters for command command.addArguments('-lah') command.addArguments('-l') // Step 4. Executing a command def res = cli.runCommand(command) // Step 5. Processing a response. println("STDOUT: " + res.getStdout())


// In a plugin's class code"This is info") log.error("This is error") // Using the static import import static com.cloudbees.flowpdf.Log.* logInfo("This is info") logError("This is error")


Map reference = [ one : 'two', three : 'four' ]; logInfo("Reference is: ", reference.toString())

Defining custom fields

You can define custom fields in the pluginInfo method of your main plugin module and retrieve them elsewhere.

Map<String, Object> pluginInfo() { return [ pluginName : '@PLUGIN_KEY@', pluginVersion : '@PLUGIN_VERSION@', configFields : ['config'], configLocations : ['ec_plugin_cfgs'], defaultConfigValues : [ authScheme : 'basic' ], configValues : [ one : 'two' ] ] }

Here is how you retrieve them:

def pluginValues = pluginObject.getPluginValues()"Value of one is: " + pluginValues['configValues']['one'])