Advertisement
Guest User

Untitled

a guest
Dec 13th, 2019
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.35 KB | None | 0 0
  1. import com.atlassian.sal.api.component.ComponentLocator
  2. import com.atlassian.confluence.pages.PageManager
  3. import com.atlassian.confluence.spaces.SpaceManager
  4. import com.atlassian.confluence.pages.Page
  5. import com.atlassian.confluence.user.UserAccessor
  6. import com.atlassian.sal.api.user.UserKey
  7. import com.atlassian.sal.api.user.UserManager
  8. import com.atlassian.confluence.core.DefaultSaveContext
  9. import com.atlassian.confluence.core.SaveContext
  10. import com.atlassian.confluence.event.events.content.page.PageEvent
  11. import com.atlassian.applinks.api.ApplicationLinkService
  12. import com.atlassian.applinks.api.application.jira.JiraApplicationType
  13. import com.atlassian.sal.api.net.Response
  14. import com.atlassian.sal.api.net.ResponseException
  15. import com.atlassian.sal.api.net.ResponseHandler
  16. import com.onresolve.scriptrunner.runner.customisers.WithPlugin
  17. import groovy.json.JsonBuilder
  18. import groovy.json.JsonSlurper
  19. import org.apache.http.util.EntityUtils
  20. import org.jsoup.Jsoup
  21. import org.jsoup.nodes.Document
  22. import org.jsoup.nodes.Element
  23. import org.joda.time.DateTime
  24. import static com.atlassian.sal.api.net.Request.MethodType.POST
  25. import static com.atlassian.sal.api.net.Request.MethodType.GET
  26. import org.apache.log4j.Level
  27. import org.apache.log4j.Logger
  28.  
  29. log = Logger.getLogger("com.tvpro.CreateIssue")
  30. log.setLevel(Level.DEBUG)
  31.  
  32. def pageManager = ComponentLocator.getComponent(PageManager)
  33. def spaceManager = ComponentLocator.getComponent(SpaceManager)
  34. def entityUtils = ComponentLocator.getComponent(EntityUtils)
  35. def profile = ComponentLocator.getComponent(UserManager)
  36. def userAccessor = ComponentLocator.getComponent(UserAccessor)
  37.  
  38. def appLinkService = ComponentLocator.getComponent(ApplicationLinkService)
  39. def appLink = appLinkService.getPrimaryApplicationLink(JiraApplicationType)
  40. def applicationLinkRequestFactory = appLink.createAuthenticatedRequestFactory()
  41.  
  42.  
  43. hits.each { page ->
  44. def text_page = page.getBodyAsString()
  45. log.info("В запрос попали следующие страницы: " + page.title)
  46. log.info("Id страниц: " + page.id)
  47. def space = spaceManager.getSpaceFromPageId(page.id)
  48. log.info("Спейсы в котором были созданы страницы: " + space)
  49.  
  50.  
  51.  
  52. def projectMapping = [
  53. HR: [prj:"HR",lead:"shakhova_ia",type:"Task"],
  54. ITSM: [prj:"ITSM",lead:"bazhenov_av",type:"Task"],
  55. PROTOCOL: [prj:"TM",lead:"vorobiev",type:"Story"],
  56. LAW: [prj:"LAW",lead:"bashirov_in",type:"Task"],
  57. ITMEETINGS: [prj:"ITTEAMLEAD",lead:"uchamprin_av",type:"Task"],
  58. MRKT: [prj:"MARKETING",lead:"malahova",type:"Task"],
  59. LOG: [prj:"LOG",lead:"sentemov_mv",type:"Task"]
  60.  
  61. ]
  62. def lead = projectMapping[space].lead
  63. def prj = projectMapping[space].prj
  64. def type = projectMapping[space].type
  65. // ==================
  66.  
  67.  
  68. def doc = Jsoup.parse(text_page)
  69. def subAss = []
  70. def table = doc.select("table").get(1) // Выбираем первую таблицу
  71. def rows = table.select("tr")
  72. def subAssigneeKey
  73. def assigneeName
  74. def body
  75. def assigneeKey
  76. def summary
  77. def description
  78. def dateNew
  79. def dateTime
  80. def dateTimeNew
  81. def keyProject
  82. for (int i = 1; i < rows.size(); i++) {
  83. def row = rows.get(i)
  84. def cols = row.select("td")
  85. summary = cols.get(1).text()
  86. description = cols.get(2).text()
  87. def subAssignee = cols.get(4).select('ac|link')
  88. //log.debug(cols)
  89. //======================================================
  90. //log.debug(subAssignee.size())
  91. subAssignee.each{
  92. def user = it.select('ri|user').attr('ri:userkey')
  93. subAssigneeKey = userAccessor.getUserByKey(new UserKey(user))
  94. subAss.add([name:subAssigneeKey.name])
  95. //log.debug(subAss)
  96. }
  97. //======================================================
  98. def assignee = cols.get(3).select('ac|link')
  99. //log.debug(assignee)
  100. if(assignee.size() != 0){
  101. def user = assignee.select('ri|user').attr('ri:userkey')
  102. assigneeName = userAccessor.getUserByKey(new UserKey(user))
  103. assigneeKey = assigneeName.name
  104. //log.debug(t.name)
  105. } else { assigneeKey = null}
  106. //=====================================================
  107. def date = cols.get(6).select('time')
  108. //log.debug(date)
  109. if (date.size() != 0 ){
  110. dateNew = date.attr('datetime')
  111. dateTime = new DateTime(dateNew).plusHours(18).toString()
  112. dateTimeNew = dateTime.replace("+03:00", "+0300")
  113. //log.debug(dateTimeNew)
  114. } else { dateTimeNew =null}
  115.  
  116. // =======================================================
  117. // Получаем ключ проекта по исполнителю из протокола
  118. //=========================================================
  119. /*
  120. if (space == "PROMO"){
  121. def jsonSlurper = new JsonSlurper()
  122. def projectLead = applicationLinkRequestFactory.createRequest(GET, "/rest/api/2/project?expand=lead")
  123. projectLead.execute(new ResponseHandler<Response>() {
  124. @Override
  125. void handle(Response responseLead) throws ResponseException {
  126. if (responseLead.statusCode != 200) {
  127. log.error("Error: ${responseLead.responseBodyAsString}")
  128. }
  129.  
  130. def prjLead = responseLead.responseBodyAsString
  131. def project = jsonSlurper.parseText(prjLead)
  132. //log.info(project)
  133. project.each {
  134. //def keyProject = it.key
  135. def leadProject = it.lead.key
  136. if (leadProject == ser){
  137. keyProject = it.key
  138. log.info(keyProject)
  139. }
  140. }
  141. }
  142. })
  143. }
  144. */
  145. //=====================================================
  146.  
  147. //=====================================================
  148.  
  149.  
  150. def bodyOnlyTM = [fields: [
  151. project : [key: prj],
  152. issuetype : [name: type],
  153. summary : summary,
  154. description: description,
  155. reporter : [name: lead],
  156. assignee : [name: assigneeKey],
  157. //priority : [result[i+4]],
  158. customfield_10500 : dateTimeNew, //deadline - дата + время
  159. customfield_12300 : subAss, //Наблюдатели
  160. security: [id: "10400"]
  161. ]
  162. ]
  163. def bodyOnOtherTM = [fields: [
  164. project : [key: prj],
  165. issuetype : [name: type],
  166. summary : summary,
  167. description: description,
  168. reporter : [name: lead],
  169. assignee : [name: assigneeKey],
  170. //priority : [result[i+4]],
  171. customfield_10500 : dateTimeNew, //deadline - дата + время
  172. customfield_12300 : subAss //Наблюдатели
  173. ]
  174. ]
  175.  
  176. if( space == "Protocol"){
  177. body = new JsonBuilder(
  178. bodyOnlyTM
  179. ).toString()
  180. } else {
  181. body = new JsonBuilder(
  182. bodyOnOtherTM
  183. ).toString()
  184. }
  185. log.info("Для страницы были заполнены следующие поля: " + body)
  186.  
  187.  
  188. def request = applicationLinkRequestFactory.createRequest(POST, "/rest/api/2/issue")
  189. .addHeader("Content-Type", "application/json")
  190. .setEntity(body)
  191. request.execute(new ResponseHandler<Response>() {
  192. @Override
  193. void handle(Response response) throws ResponseException {
  194. if (response.statusCode != 201) {
  195. log.info("Creating Jira issue failed: ${response.responseBodyAsString}")
  196. }
  197. //========================================================================================
  198. // Создание ссылки на WIKI
  199. //========================================================================================
  200. def issueData = (new JsonSlurper()).parseText(response.getResponseBodyAsString())
  201. def linkWiki = new JsonBuilder([
  202. globalId: "appId=af34f21d-fdf9-3a94-b4fe-70ae558c9259&pageId=${page.id}",
  203. application: [type: "com.atlassian.confluence"],
  204. relationship:"Wiki Page",
  205. object: [
  206. url:"https://wiki.sands.ru/pages/viewpage.action?pageId=${page.id}",
  207. title:"Wiki Page",
  208. ]
  209. ]).toString()
  210. def linkW = applicationLinkRequestFactory.createRequest(POST, "/rest/api/2/issue/${issueData.key}/remotelink")
  211. .addHeader("Content-Type", "application/json")
  212. .setEntity(linkWiki)
  213.  
  214. linkW.execute(new ResponseHandler<Response>() {
  215. @Override
  216. void handle(Response responseLink) throws ResponseException {
  217. if (responseLink.statusCode != 201) {
  218. log.info("Creating Link failed: ${responseLink.responseBodyAsString}")
  219. }
  220. }
  221. })
  222. //=======================================================================================
  223. subAss = []
  224. }
  225. })
  226. }
  227. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement