Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import com.atlassian.sal.api.component.ComponentLocator
- import com.atlassian.confluence.pages.PageManager
- import com.atlassian.confluence.spaces.SpaceManager
- import com.atlassian.confluence.pages.Page
- import com.atlassian.confluence.user.UserAccessor
- import com.atlassian.sal.api.user.UserKey
- import com.atlassian.sal.api.user.UserManager
- import com.atlassian.confluence.core.DefaultSaveContext
- import com.atlassian.confluence.core.SaveContext
- import com.atlassian.confluence.event.events.content.page.PageEvent
- import com.atlassian.applinks.api.ApplicationLinkService
- import com.atlassian.applinks.api.application.jira.JiraApplicationType
- import com.atlassian.sal.api.net.Response
- import com.atlassian.sal.api.net.ResponseException
- import com.atlassian.sal.api.net.ResponseHandler
- import com.onresolve.scriptrunner.runner.customisers.WithPlugin
- import groovy.json.JsonBuilder
- import groovy.json.JsonSlurper
- import org.apache.http.util.EntityUtils
- import org.jsoup.Jsoup
- import org.jsoup.nodes.Document
- import org.jsoup.nodes.Element
- import org.joda.time.DateTime
- import static com.atlassian.sal.api.net.Request.MethodType.POST
- import static com.atlassian.sal.api.net.Request.MethodType.GET
- import org.apache.log4j.Level
- import org.apache.log4j.Logger
- log = Logger.getLogger("com.tvpro.CreateIssue")
- log.setLevel(Level.DEBUG)
- def pageManager = ComponentLocator.getComponent(PageManager)
- def spaceManager = ComponentLocator.getComponent(SpaceManager)
- def entityUtils = ComponentLocator.getComponent(EntityUtils)
- def profile = ComponentLocator.getComponent(UserManager)
- def userAccessor = ComponentLocator.getComponent(UserAccessor)
- def appLinkService = ComponentLocator.getComponent(ApplicationLinkService)
- def appLink = appLinkService.getPrimaryApplicationLink(JiraApplicationType)
- def applicationLinkRequestFactory = appLink.createAuthenticatedRequestFactory()
- hits.each { page ->
- def text_page = page.getBodyAsString()
- log.info("В запрос попали следующие страницы: " + page.title)
- log.info("Id страниц: " + page.id)
- def space = spaceManager.getSpaceFromPageId(page.id)
- log.info("Спейсы в котором были созданы страницы: " + space)
- def projectMapping = [
- HR: [prj:"HR",lead:"shakhova_ia",type:"Task"],
- ITSM: [prj:"ITSM",lead:"bazhenov_av",type:"Task"],
- PROTOCOL: [prj:"TM",lead:"vorobiev",type:"Story"],
- LAW: [prj:"LAW",lead:"bashirov_in",type:"Task"],
- ITMEETINGS: [prj:"ITTEAMLEAD",lead:"uchamprin_av",type:"Task"],
- MRKT: [prj:"MARKETING",lead:"malahova",type:"Task"],
- LOG: [prj:"LOG",lead:"sentemov_mv",type:"Task"]
- ]
- def lead = projectMapping[space].lead
- def prj = projectMapping[space].prj
- def type = projectMapping[space].type
- // ==================
- def doc = Jsoup.parse(text_page)
- def subAss = []
- def table = doc.select("table").get(1) // Выбираем первую таблицу
- def rows = table.select("tr")
- def subAssigneeKey
- def assigneeName
- def body
- def assigneeKey
- def summary
- def description
- def dateNew
- def dateTime
- def dateTimeNew
- def keyProject
- for (int i = 1; i < rows.size(); i++) {
- def row = rows.get(i)
- def cols = row.select("td")
- summary = cols.get(1).text()
- description = cols.get(2).text()
- def subAssignee = cols.get(4).select('ac|link')
- //log.debug(cols)
- //======================================================
- //log.debug(subAssignee.size())
- subAssignee.each{
- def user = it.select('ri|user').attr('ri:userkey')
- subAssigneeKey = userAccessor.getUserByKey(new UserKey(user))
- subAss.add([name:subAssigneeKey.name])
- //log.debug(subAss)
- }
- //======================================================
- def assignee = cols.get(3).select('ac|link')
- //log.debug(assignee)
- if(assignee.size() != 0){
- def user = assignee.select('ri|user').attr('ri:userkey')
- assigneeName = userAccessor.getUserByKey(new UserKey(user))
- assigneeKey = assigneeName.name
- //log.debug(t.name)
- } else { assigneeKey = null}
- //=====================================================
- def date = cols.get(6).select('time')
- //log.debug(date)
- if (date.size() != 0 ){
- dateNew = date.attr('datetime')
- dateTime = new DateTime(dateNew).plusHours(18).toString()
- dateTimeNew = dateTime.replace("+03:00", "+0300")
- //log.debug(dateTimeNew)
- } else { dateTimeNew =null}
- // =======================================================
- // Получаем ключ проекта по исполнителю из протокола
- //=========================================================
- /*
- if (space == "PROMO"){
- def jsonSlurper = new JsonSlurper()
- def projectLead = applicationLinkRequestFactory.createRequest(GET, "/rest/api/2/project?expand=lead")
- projectLead.execute(new ResponseHandler<Response>() {
- @Override
- void handle(Response responseLead) throws ResponseException {
- if (responseLead.statusCode != 200) {
- log.error("Error: ${responseLead.responseBodyAsString}")
- }
- def prjLead = responseLead.responseBodyAsString
- def project = jsonSlurper.parseText(prjLead)
- //log.info(project)
- project.each {
- //def keyProject = it.key
- def leadProject = it.lead.key
- if (leadProject == ser){
- keyProject = it.key
- log.info(keyProject)
- }
- }
- }
- })
- }
- */
- //=====================================================
- //=====================================================
- def bodyOnlyTM = [fields: [
- project : [key: prj],
- issuetype : [name: type],
- summary : summary,
- description: description,
- reporter : [name: lead],
- assignee : [name: assigneeKey],
- //priority : [result[i+4]],
- customfield_10500 : dateTimeNew, //deadline - дата + время
- customfield_12300 : subAss, //Наблюдатели
- security: [id: "10400"]
- ]
- ]
- def bodyOnOtherTM = [fields: [
- project : [key: prj],
- issuetype : [name: type],
- summary : summary,
- description: description,
- reporter : [name: lead],
- assignee : [name: assigneeKey],
- //priority : [result[i+4]],
- customfield_10500 : dateTimeNew, //deadline - дата + время
- customfield_12300 : subAss //Наблюдатели
- ]
- ]
- if( space == "Protocol"){
- body = new JsonBuilder(
- bodyOnlyTM
- ).toString()
- } else {
- body = new JsonBuilder(
- bodyOnOtherTM
- ).toString()
- }
- log.info("Для страницы были заполнены следующие поля: " + body)
- def request = applicationLinkRequestFactory.createRequest(POST, "/rest/api/2/issue")
- .addHeader("Content-Type", "application/json")
- .setEntity(body)
- request.execute(new ResponseHandler<Response>() {
- @Override
- void handle(Response response) throws ResponseException {
- if (response.statusCode != 201) {
- log.info("Creating Jira issue failed: ${response.responseBodyAsString}")
- }
- //========================================================================================
- // Создание ссылки на WIKI
- //========================================================================================
- def issueData = (new JsonSlurper()).parseText(response.getResponseBodyAsString())
- def linkWiki = new JsonBuilder([
- globalId: "appId=af34f21d-fdf9-3a94-b4fe-70ae558c9259&pageId=${page.id}",
- application: [type: "com.atlassian.confluence"],
- relationship:"Wiki Page",
- object: [
- url:"https://wiki.sands.ru/pages/viewpage.action?pageId=${page.id}",
- title:"Wiki Page",
- ]
- ]).toString()
- def linkW = applicationLinkRequestFactory.createRequest(POST, "/rest/api/2/issue/${issueData.key}/remotelink")
- .addHeader("Content-Type", "application/json")
- .setEntity(linkWiki)
- linkW.execute(new ResponseHandler<Response>() {
- @Override
- void handle(Response responseLink) throws ResponseException {
- if (responseLink.statusCode != 201) {
- log.info("Creating Link failed: ${responseLink.responseBodyAsString}")
- }
- }
- })
- //=======================================================================================
- subAss = []
- }
- })
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement