Работа с конфигуратором проекта и ScriptRunner для Jira синхронный импорт - malikovalibek/groovyForJira GitHub Wiki

Конфигуратор проекта может выполнять большинство операций в двух режимах: асинхронном и синхронном. Асинхронный режим - это то, что видят большинство конечных пользователей, операция запускается в фоновом потоке, вы можете запросить ее ход (например, чтобы отобразить индикатор выполнения), и когда он будет завершен, можно получить результаты операции и сделай что-нибудь с ними. Это уместно, когда операция будет выполняться долго, обычно потому, что экспорт / импорт подразумевает большие объемы конфигурации и данных. В противном случае, если большинство ваших операций будет выполняться в течение ограниченного времени, вы можете просто использовать синхронные методы.

// Required Imports

import com.atlassian.jira.component.ComponentAccessor import com.atlassian.jira.task.TaskProgressSink import com.awnaba.projectconfigurator.operationsapi.ConfigImportResult import com.awnaba.projectconfigurator.operationsapi.ConfigOpCallResult import com.awnaba.projectconfigurator.operationsapi.ConfigOpFullProcessResult import com.awnaba.projectconfigurator.operationsapi.ProjectConfigImporter import com.onresolve.scriptrunner.runner.customisers.WithPlugin

import static com.onresolve.scriptrunner.canned.util.OutputFormatter.markupBuilder

// The required annotation to enable access to the functionality provided by the plugin within our script @WithPlugin("com.awnaba.projectconfigurator.projectconfigurator")

// Get an instance of the import method def importer = ComponentAccessor.getOSGiComponentInstanceOfType(ProjectConfigImporter)

// Specify the path to the export file def exportFile = "/tmp/export.xml"

// Perform the import if the file is valid try { // Extract the contents of the export file to a String that the import method can use def fileContents = new File(exportFile).text

// The booleans below allow you to configure the import options you require and match the checkboxes displayed inside the user interface

// Set to true if you wish to apply the changes as by default only a simulated import is run. boolean applyChanges = false

// Set to true if you want to create any referenced projects as part of the import boolean CreateExtraProjects = false

// Set to true if you wish to use smart custom field contexts boolean smartCustomFieldContexts = false

// Set to true if you wish to try to publish drafs as part of the import boolean publishDrafts = false

// Set to true to continue if any errors occur related to Jira Issue Filters or Dashboards boolean continueOnErrorsWithDashboardsandFilters = false

// A list to specify any configuration objects which we do not wish to import. String[] doNotLoad = []

// Construct a new ConfigOpFullProcessResult object which will store the results of the configuration import // Requires the following parameters of XML config, applyChanges,createExtraProjects,smartCFContexts,publishDrafts,continueOnDashboardFilterErrors,doNotLoadObjects as well as an instance of the TaskProgressSink object. def importResult = importer.importConfigurationSynchronously(fileContents.toString(), applyChanges, CreateExtraProjects, smartCustomFieldContexts, publishDrafts, continueOnErrorsWithDashboardsandFilters, doNotLoad, TaskProgressSink.NULL_SINK) as ConfigOpFullProcessResult<ProjectConfigImporter.ReturnCallCode, ? extends ConfigImportResult>

// Check if the import completed successfully and if so display the results def callResult = importResult.callResult as ConfigOpCallResult def callReturnCode = callResult.returnCode

// If the import failed notify the user // Possible return codes that can be checked = IMPORT_STARTED, NOT_LOGGED_IN, UNAUTHORIZED, UNLICENSED, ERROR_READING_CONFIG_FILE, IMPORT_ALREADY_RUNNING if (callReturnCode != null && callReturnCode != ProjectConfigImporter.ReturnCallCode.IMPORT_STARTED) { return "The import did not launch successfully. Launching failed with a return code of " + callReturnCode.toString() // If the import was successful display the results } // get the results of the import ProjectConfigImporter.ReturnOpCode opCode = importResult.finalResult.returnCode String message = opCode == ProjectConfigImporter.ReturnOpCode.SUCCESS ? importResult.finalResult.successMessage : "Import failed"

markupBuilder { p(opCode.name()) p(message) pre(importResult.finalResult.loadTrace) }

// If an invalid file is found print an exception on screen } catch (FileNotFoundException e) { markupBuilder { p('You must provide a valid file:') p(e) } }