Advertisement
Guest User

Untitled

a guest
Dec 19th, 2018
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Groovy 12.36 KB | None | 0 0
  1. import com.atlassian.applinks.api.ApplicationLink
  2. import com.atlassian.applinks.api.ApplicationLinkService
  3. import com.atlassian.applinks.api.application.confluence.ConfluenceApplicationType
  4. import com.atlassian.jira.bc.issue.properties.IssuePropertyService
  5. import com.atlassian.jira.component.ComponentAccessor
  6. import com.atlassian.jira.config.util.JiraHome
  7. import com.atlassian.jira.entity.property.EntityPropertyService
  8. import com.atlassian.jira.issue.Issue
  9. import com.atlassian.jira.issue.MutableIssue
  10. import com.atlassian.jira.user.ApplicationUser
  11. import com.atlassian.jira.util.PathUtils
  12. import com.atlassian.sal.api.net.RequestFilePart
  13. import groovy.json.JsonOutput
  14. import groovy.json.JsonSlurper
  15. import org.apache.http.HttpEntity
  16. import org.apache.http.HttpHeaders
  17. import org.apache.http.HttpResponse
  18. import org.apache.http.client.config.RequestConfig
  19. import org.apache.http.client.methods.HttpPost
  20. import org.apache.http.client.methods.HttpPut
  21. import org.apache.http.client.utils.URIBuilder
  22. import org.apache.http.conn.ssl.*
  23. import org.apache.http.entity.ContentType
  24. import org.apache.http.entity.mime.HttpMultipartMode
  25. import org.apache.http.entity.mime.MultipartEntityBuilder
  26. import org.apache.http.entity.mime.content.FileBody
  27. import org.apache.http.entity.mime.content.StringBody
  28. import org.apache.http.impl.client.HttpClientBuilder
  29. import org.apache.log4j.Logger
  30. import java.io.IOException
  31. import java.security.SecureRandom
  32. import java.security.cert.CertificateException
  33. import java.security.cert.X509Certificate
  34.  
  35. import javax.net.ssl.HostnameVerifier
  36. import javax.net.ssl.HttpsURLConnection
  37. import javax.net.ssl.SSLContext
  38. import javax.net.ssl.SSLException
  39. import javax.net.ssl.SSLSession
  40. import javax.net.ssl.SSLSocket
  41. import javax.net.ssl.TrustManager
  42. import javax.net.ssl.X509TrustManager
  43. import org.apache.http.entity.mime.content.StringBody
  44. import java.nio.charset.Charset
  45.  
  46. import org.apache.commons.logging.Log
  47. import org.apache.commons.logging.LogFactory
  48. import org.apache.http.conn.ssl.X509HostnameVerifier
  49.  
  50. import javax.net.ssl.*
  51. import java.io.File
  52. import java.nio.charset.StandardCharsets
  53.  
  54.  
  55. public class UnsafeSSLHelper {
  56.     private static Log LOG = LogFactory.getLog(UnsafeSSLHelper.class.getName())
  57.     private static boolean warnUnsecureMode = false
  58.     /**
  59.      * This method could be called before asking "https://" uri to accept any invalid ssl certificate.
  60.      *
  61.      * src: http://stackoverflow.com/questions/1828775/how-to-handle-invalid-ssl-certificates-with-apache-httpclient
  62.      *
  63.      * Usage
  64.      *
  65.      * common usage sample:
  66.      *    (new UnsafeSSLHelper()).ignoreSSLCertif()
  67.      *    // then make your https connection
  68.      *
  69.      * Apache HttpClient example:
  70.      UnsafeSSLHelper unsafeSSLHelper = new UnsafeSSLHelper()
  71.      CloseableHttpClient client = HttpClientBuilder
  72.      .create()
  73.      .setSslcontext(unsafeSSLHelper.createUnsecureSSLContext())
  74.      .setHostnameVerifier(unsafeSSLHelper.getPassiveX509HostnameVerifier())
  75.      .build()
  76.      */
  77.     public SSLContext ignoreSSLCertif() {
  78.         if (!warnUnsecureMode) {
  79.             LOG.warn("SSL Exchanges: UNSECURE mode activated")
  80.         }
  81.         warnUnsecureMode = true
  82.         HostnameVerifier allHostsValid = getPassiveHostnameVerifier()
  83.         HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid)
  84.         // Install the all-trusting trust manager
  85.         SSLContext sc = createUnsecureSSLContext()
  86.         try {
  87.             SSLContext.setDefault(sc)
  88.             HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory())
  89.         } catch (Exception e) {
  90.             LOG.warn(String.format("SSL Exchanges: UNSECURE mode exception : %s", e.getMessage()), e)
  91.         }
  92.         return sc
  93.     }
  94.  
  95.     public SSLContext createUnsecureSSLContext() {
  96.         SSLContext sc = null
  97.         try {
  98.             TrustManager[] trustAllCerts = new TrustManager[1]
  99.             trustAllCerts[0] = getPassiveTrustManager()
  100.             sc = SSLContext.getInstance("TLS")
  101.             sc.init(null, trustAllCerts, new SecureRandom())
  102.         } catch (Exception e) {
  103.             String msg = "error while creating unsecure SSLContext"
  104.             LOG.error(msg, e)
  105.             throw new RuntimeException(msg, e)
  106.         }
  107.         return sc
  108.     }
  109.  
  110.     public HostnameVerifier getPassiveHostnameVerifier() {
  111.         return new HostnameVerifier() {
  112.             public boolean verify(String hostname, SSLSession session) {
  113.                 return true
  114.             }
  115.         }
  116.     }
  117.  
  118.     public X509TrustManager getPassiveTrustManager() {
  119.         return new X509TrustManager() {
  120.  
  121.             public X509Certificate[] getAcceptedIssuers() {
  122.                 return null
  123.             }
  124.  
  125.             public void checkServerTrusted(X509Certificate[] arg0, String arg1)
  126.                     throws CertificateException {
  127.             }
  128.  
  129.             public void checkClientTrusted(X509Certificate[] arg0, String arg1)
  130.                     throws CertificateException {
  131.             }
  132.         }
  133.     }
  134.  
  135.     public X509HostnameVerifier getPassiveX509HostnameVerifier() {
  136.         return new X509HostnameVerifier() {
  137.             public boolean verify(String arg0, SSLSession arg1) {
  138.                 return true
  139.             }
  140.  
  141.             public void verify(String host, SSLSocket ssl)
  142.                     throws IOException {
  143.             }
  144.  
  145.             public void verify(String host, X509Certificate cert)
  146.                     throws SSLException {
  147.             }
  148.  
  149.             public void verify(String host, String[] cns,
  150.                                String[] subjectAlts) throws SSLException {
  151.             }
  152.         }
  153.     }
  154. }
  155.  
  156.  
  157.  
  158. def als = ComponentAccessor.getComponent(ApplicationLinkService.class)
  159. def am = ComponentAccessor.attachmentManager
  160. def pam = ComponentAccessor.attachmentPathManager
  161. def ips = ComponentAccessor.getComponent(IssuePropertyService.class)
  162.  
  163. def ATTACHMENT_PROPERTY_KEY = "sk.eea.jira.pyro.upload.attachments"
  164. def PAGE_PROPERTY_KEY = "confluence.page-id"
  165. def BASE_JSON = "{\"data\": {}}"
  166.  
  167. MutableIssue issue = binding.variables.get("issue") as MutableIssue ?: ComponentAccessor.issueManager.getIssueObject("HR-124")
  168. String jiraHome = ComponentAccessor.getComponentOfType(JiraHome.class).getHome()
  169. def user = ComponentAccessor.jiraAuthenticationContext.user
  170.  
  171. def log = Logger.getLogger("com.onresolve.jira.groovy.groovyrunner")//add to logging and profiling
  172. def result = ""
  173. def LINE = "</br>"
  174.  
  175.  
  176. def primaryConfluence = als.getPrimaryApplicationLink(ConfluenceApplicationType.class) as ApplicationLink
  177. if (!primaryConfluence) {
  178.     log.error("No primary Confluence link was defined")
  179.     return
  180. }
  181.  
  182. def attachmentsJSON = getProperty(ips, user, issue, ATTACHMENT_PROPERTY_KEY)
  183. def pageId = getProperty(ips, user, issue, PAGE_PROPERTY_KEY)
  184.  
  185. def calculateFolderById(issue) {
  186.     Double d = issue.id / 10000
  187.     return "/${d.intValue()}0000"
  188. }
  189.  
  190. if (pageId) {
  191.     if (!attachmentsJSON || attachmentsJSON == "{}") {
  192.         attachmentsJSON = BASE_JSON
  193.     }
  194.  
  195.     def savedAttachments = new JsonSlurper().parseText(attachmentsJSON)
  196.  
  197.     log.debug("saved Attachments: " + savedAttachments)
  198.  
  199.     //Prevent same name of attachments. Only last attachment with same name will be approved
  200.     def attachmentMap = [:]
  201.     am.getAttachments(issue)?.each { attachment ->
  202.         def toUpload
  203.         def fromMap = attachmentMap.get(attachment.filename)
  204.         if (!fromMap) {
  205.             toUpload = attachment
  206.         } else {
  207.             if (attachment.created.after(fromMap.created)) {
  208.                 toUpload = attachment
  209.             } else {
  210.                 toUpload = fromMap
  211.             }
  212.         }
  213.  
  214.         attachmentMap.put(toUpload.filename, toUpload)
  215.     }
  216.  
  217.     //attachment to fileparts
  218.     attachmentMap?.each { fileName, attachment ->
  219.  
  220.         def projNumberPath = issue.projectObject.key + calculateFolderById(issue)
  221.         String path = PathUtils.joinPaths(pam.attachmentPath, projNumberPath, issue.key, attachment.id.toString())
  222.  
  223.         def file = new File(path)
  224.         if (file.exists()) {
  225.             def filePart = new RequestFilePart("application/octet-stream", new String("životopis.txt".getBytes("windows-1250"), "windows-1250"), file, "file")
  226.             //create Confluence REST URL and fill data
  227.             def confluencePATH = "rest/api/content/" + pageId + "/child/attachment"
  228.  
  229.             //if property contains attachment id, attachment will be updated
  230.             def tempSaved = savedAttachments.get("data")
  231.             if (tempSaved.get(fileName)) {
  232.                 confluencePATH += "/" + tempSaved.get(fileName) + "/data"
  233.             }
  234.  
  235.             URIBuilder builder = URIBuilder.newInstance()
  236.             builder.setPath(primaryConfluence.getRpcUrl().toString() + "/" + confluencePATH)
  237.             URL url = builder.build().toURL()
  238.  
  239.  
  240.  
  241.  
  242.  
  243.  
  244.             def encodingName = "UTF-8"
  245.  
  246.  
  247.             HttpPost post = new HttpPost("https://breakfast.eea.sk/confluence/rest/api/content/1573441/child/attachment/")
  248.             FileBody fileBody = new FileBody(file, ContentType.MULTIPART_FORM_DATA)
  249.  
  250.             MultipartEntityBuilder mbuilder = MultipartEntityBuilder.create()
  251.             mbuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
  252.  
  253.             mbuilder.addPart("file", fileBody)
  254.             mbuilder.setCharset(Charset.forName(encodingName))
  255.             mbuilder.setContentType(ContentType.MULTIPART_FORM_DATA)
  256. //            mbuilder.addBinaryBody("file", file,
  257. //                    ContentType.MULTIPART_FORM_DATA, fileName)
  258.  
  259.             HttpEntity entity = mbuilder.build()
  260.  
  261.             def base64utf8 = "eea-admin:Aeboh4sahs"
  262.             post.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + new Base64().getEncoder().encodeToString(base64utf8.getBytes(StandardCharsets.UTF_8)))
  263.             post.setHeader("X-Atlassian-Token","no-check")
  264.             post.setEntity(entity)
  265.             post.setHeader("Accept", "application/json")
  266.             post.setHeader("Content-type", "multipart/form-data")
  267.             post.setHeader("Host", "https://breakfast.eea.sk/confluence")
  268.             post.setHeader("Accept-Encoding", encodingName)
  269.  
  270. //            def TIME_OUT = 5 * 1000 // 5 sec timeout
  271. //            RequestConfig config = RequestConfig.custom().setConnectTimeout(TIME_OUT).setConnectionRequestTimeout(TIME_OUT).setSocketTimeout(TIME_OUT).build()
  272.  
  273.             UnsafeSSLHelper unsafeSSLHelper = new UnsafeSSLHelper()
  274.             def client = HttpClientBuilder.create()
  275.                     .setSslcontext(unsafeSSLHelper.createUnsecureSSLContext())
  276.                     .setHostnameVerifier(unsafeSSLHelper.getPassiveX509HostnameVerifier())
  277.                     .build()
  278.  
  279.  
  280.  
  281.             def response = null
  282.             try {
  283.                 response = client.execute(post)
  284.             } catch (Exception e) {
  285.                 log.error("[${issue.key}] Failed to notify ABS server. Error: ${e.message}")
  286.             }
  287.  
  288.             client.close()
  289.             def statusCode = response?.statusLine?.statusCode
  290.  
  291.             result += response.toString() + LINE
  292.  
  293.  
  294.         } else log.error "File [" + path + "] not exist"
  295.     }
  296.  
  297.     def json = JsonOutput.toJson(savedAttachments)
  298.     result += json + LINE
  299.     setProperty(ips, user, issue, ATTACHMENT_PROPERTY_KEY, json)
  300. } else {
  301.     log.error("Page id not stored")
  302. }
  303.  
  304. private String convertResponseStreamToString(java.io.InputStream is) {
  305.     if (is == null) return ""
  306.     java.util.Scanner s = new java.util.Scanner(is)
  307.     s.useDelimiter("\\A")
  308.     String streamString = s.hasNext() ? s.next() : ""
  309.     s.close()
  310.     return streamString
  311. }
  312.  
  313. private String getProperty(IssuePropertyService ips, ApplicationUser user, Issue issue, String property) {
  314.     return ips.getProperty(user, issue.id, property).getEntityProperty().getOrNull()?.value
  315. }
  316.  
  317. private boolean setProperty(IssuePropertyService ips, ApplicationUser user, Issue issue, String property, String value) {
  318.     def validation = ips.validateSetProperty(user, issue.id, new EntityPropertyService.PropertyInput(value, property))
  319.     if (validation.valid) {
  320.         ips.setProperty(user, validation)
  321.         log.error("Stored page id " + value + " to issue property " + property)
  322.         return true
  323.     } else {
  324.         log.error("Failed to store page id " + value + " to issue property " + property + ": " + validation.errorCollection)
  325.         return false
  326.     }
  327. }
  328.  
  329. return result
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement