Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import com.atlassian.applinks.api.ApplicationLink
- import com.atlassian.applinks.api.ApplicationLinkService
- import com.atlassian.applinks.api.application.confluence.ConfluenceApplicationType
- import com.atlassian.jira.bc.issue.properties.IssuePropertyService
- import com.atlassian.jira.component.ComponentAccessor
- import com.atlassian.jira.config.util.JiraHome
- import com.atlassian.jira.entity.property.EntityPropertyService
- import com.atlassian.jira.issue.Issue
- import com.atlassian.jira.issue.MutableIssue
- import com.atlassian.jira.user.ApplicationUser
- import com.atlassian.jira.util.PathUtils
- import com.atlassian.sal.api.net.RequestFilePart
- import groovy.json.JsonOutput
- import groovy.json.JsonSlurper
- import org.apache.http.HttpEntity
- import org.apache.http.HttpHeaders
- import org.apache.http.HttpResponse
- import org.apache.http.client.config.RequestConfig
- import org.apache.http.client.methods.HttpPost
- import org.apache.http.client.methods.HttpPut
- import org.apache.http.client.utils.URIBuilder
- import org.apache.http.conn.ssl.*
- import org.apache.http.entity.ContentType
- import org.apache.http.entity.mime.HttpMultipartMode
- import org.apache.http.entity.mime.MultipartEntityBuilder
- import org.apache.http.entity.mime.content.FileBody
- import org.apache.http.entity.mime.content.StringBody
- import org.apache.http.impl.client.HttpClientBuilder
- import org.apache.log4j.Logger
- import java.io.IOException
- import java.security.SecureRandom
- import java.security.cert.CertificateException
- import java.security.cert.X509Certificate
- import javax.net.ssl.HostnameVerifier
- import javax.net.ssl.HttpsURLConnection
- import javax.net.ssl.SSLContext
- import javax.net.ssl.SSLException
- import javax.net.ssl.SSLSession
- import javax.net.ssl.SSLSocket
- import javax.net.ssl.TrustManager
- import javax.net.ssl.X509TrustManager
- import org.apache.http.entity.mime.content.StringBody
- import java.nio.charset.Charset
- import org.apache.commons.logging.Log
- import org.apache.commons.logging.LogFactory
- import org.apache.http.conn.ssl.X509HostnameVerifier
- import javax.net.ssl.*
- import java.io.File
- import java.nio.charset.StandardCharsets
- public class UnsafeSSLHelper {
- private static Log LOG = LogFactory.getLog(UnsafeSSLHelper.class.getName())
- private static boolean warnUnsecureMode = false
- /**
- * This method could be called before asking "https://" uri to accept any invalid ssl certificate.
- *
- * src: http://stackoverflow.com/questions/1828775/how-to-handle-invalid-ssl-certificates-with-apache-httpclient
- *
- * Usage
- *
- * common usage sample:
- * (new UnsafeSSLHelper()).ignoreSSLCertif()
- * // then make your https connection
- *
- * Apache HttpClient example:
- UnsafeSSLHelper unsafeSSLHelper = new UnsafeSSLHelper()
- CloseableHttpClient client = HttpClientBuilder
- .create()
- .setSslcontext(unsafeSSLHelper.createUnsecureSSLContext())
- .setHostnameVerifier(unsafeSSLHelper.getPassiveX509HostnameVerifier())
- .build()
- */
- public SSLContext ignoreSSLCertif() {
- if (!warnUnsecureMode) {
- LOG.warn("SSL Exchanges: UNSECURE mode activated")
- }
- warnUnsecureMode = true
- HostnameVerifier allHostsValid = getPassiveHostnameVerifier()
- HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid)
- // Install the all-trusting trust manager
- SSLContext sc = createUnsecureSSLContext()
- try {
- SSLContext.setDefault(sc)
- HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory())
- } catch (Exception e) {
- LOG.warn(String.format("SSL Exchanges: UNSECURE mode exception : %s", e.getMessage()), e)
- }
- return sc
- }
- public SSLContext createUnsecureSSLContext() {
- SSLContext sc = null
- try {
- TrustManager[] trustAllCerts = new TrustManager[1]
- trustAllCerts[0] = getPassiveTrustManager()
- sc = SSLContext.getInstance("TLS")
- sc.init(null, trustAllCerts, new SecureRandom())
- } catch (Exception e) {
- String msg = "error while creating unsecure SSLContext"
- LOG.error(msg, e)
- throw new RuntimeException(msg, e)
- }
- return sc
- }
- public HostnameVerifier getPassiveHostnameVerifier() {
- return new HostnameVerifier() {
- public boolean verify(String hostname, SSLSession session) {
- return true
- }
- }
- }
- public X509TrustManager getPassiveTrustManager() {
- return new X509TrustManager() {
- public X509Certificate[] getAcceptedIssuers() {
- return null
- }
- public void checkServerTrusted(X509Certificate[] arg0, String arg1)
- throws CertificateException {
- }
- public void checkClientTrusted(X509Certificate[] arg0, String arg1)
- throws CertificateException {
- }
- }
- }
- public X509HostnameVerifier getPassiveX509HostnameVerifier() {
- return new X509HostnameVerifier() {
- public boolean verify(String arg0, SSLSession arg1) {
- return true
- }
- public void verify(String host, SSLSocket ssl)
- throws IOException {
- }
- public void verify(String host, X509Certificate cert)
- throws SSLException {
- }
- public void verify(String host, String[] cns,
- String[] subjectAlts) throws SSLException {
- }
- }
- }
- }
- def als = ComponentAccessor.getComponent(ApplicationLinkService.class)
- def am = ComponentAccessor.attachmentManager
- def pam = ComponentAccessor.attachmentPathManager
- def ips = ComponentAccessor.getComponent(IssuePropertyService.class)
- def ATTACHMENT_PROPERTY_KEY = "sk.eea.jira.pyro.upload.attachments"
- def PAGE_PROPERTY_KEY = "confluence.page-id"
- def BASE_JSON = "{\"data\": {}}"
- MutableIssue issue = binding.variables.get("issue") as MutableIssue ?: ComponentAccessor.issueManager.getIssueObject("HR-124")
- String jiraHome = ComponentAccessor.getComponentOfType(JiraHome.class).getHome()
- def user = ComponentAccessor.jiraAuthenticationContext.user
- def log = Logger.getLogger("com.onresolve.jira.groovy.groovyrunner")//add to logging and profiling
- def result = ""
- def LINE = "</br>"
- def primaryConfluence = als.getPrimaryApplicationLink(ConfluenceApplicationType.class) as ApplicationLink
- if (!primaryConfluence) {
- log.error("No primary Confluence link was defined")
- return
- }
- def attachmentsJSON = getProperty(ips, user, issue, ATTACHMENT_PROPERTY_KEY)
- def pageId = getProperty(ips, user, issue, PAGE_PROPERTY_KEY)
- def calculateFolderById(issue) {
- Double d = issue.id / 10000
- return "/${d.intValue()}0000"
- }
- if (pageId) {
- if (!attachmentsJSON || attachmentsJSON == "{}") {
- attachmentsJSON = BASE_JSON
- }
- def savedAttachments = new JsonSlurper().parseText(attachmentsJSON)
- log.debug("saved Attachments: " + savedAttachments)
- //Prevent same name of attachments. Only last attachment with same name will be approved
- def attachmentMap = [:]
- am.getAttachments(issue)?.each { attachment ->
- def toUpload
- def fromMap = attachmentMap.get(attachment.filename)
- if (!fromMap) {
- toUpload = attachment
- } else {
- if (attachment.created.after(fromMap.created)) {
- toUpload = attachment
- } else {
- toUpload = fromMap
- }
- }
- attachmentMap.put(toUpload.filename, toUpload)
- }
- //attachment to fileparts
- attachmentMap?.each { fileName, attachment ->
- def projNumberPath = issue.projectObject.key + calculateFolderById(issue)
- String path = PathUtils.joinPaths(pam.attachmentPath, projNumberPath, issue.key, attachment.id.toString())
- def file = new File(path)
- if (file.exists()) {
- def filePart = new RequestFilePart("application/octet-stream", new String("životopis.txt".getBytes("windows-1250"), "windows-1250"), file, "file")
- //create Confluence REST URL and fill data
- def confluencePATH = "rest/api/content/" + pageId + "/child/attachment"
- //if property contains attachment id, attachment will be updated
- def tempSaved = savedAttachments.get("data")
- if (tempSaved.get(fileName)) {
- confluencePATH += "/" + tempSaved.get(fileName) + "/data"
- }
- URIBuilder builder = URIBuilder.newInstance()
- builder.setPath(primaryConfluence.getRpcUrl().toString() + "/" + confluencePATH)
- URL url = builder.build().toURL()
- def encodingName = "UTF-8"
- HttpPost post = new HttpPost("https://breakfast.eea.sk/confluence/rest/api/content/1573441/child/attachment/")
- FileBody fileBody = new FileBody(file, ContentType.MULTIPART_FORM_DATA)
- MultipartEntityBuilder mbuilder = MultipartEntityBuilder.create()
- mbuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
- mbuilder.addPart("file", fileBody)
- mbuilder.setCharset(Charset.forName(encodingName))
- mbuilder.setContentType(ContentType.MULTIPART_FORM_DATA)
- // mbuilder.addBinaryBody("file", file,
- // ContentType.MULTIPART_FORM_DATA, fileName)
- HttpEntity entity = mbuilder.build()
- def base64utf8 = "eea-admin:Aeboh4sahs"
- post.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + new Base64().getEncoder().encodeToString(base64utf8.getBytes(StandardCharsets.UTF_8)))
- post.setHeader("X-Atlassian-Token","no-check")
- post.setEntity(entity)
- post.setHeader("Accept", "application/json")
- post.setHeader("Content-type", "multipart/form-data")
- post.setHeader("Host", "https://breakfast.eea.sk/confluence")
- post.setHeader("Accept-Encoding", encodingName)
- // def TIME_OUT = 5 * 1000 // 5 sec timeout
- // RequestConfig config = RequestConfig.custom().setConnectTimeout(TIME_OUT).setConnectionRequestTimeout(TIME_OUT).setSocketTimeout(TIME_OUT).build()
- UnsafeSSLHelper unsafeSSLHelper = new UnsafeSSLHelper()
- def client = HttpClientBuilder.create()
- .setSslcontext(unsafeSSLHelper.createUnsecureSSLContext())
- .setHostnameVerifier(unsafeSSLHelper.getPassiveX509HostnameVerifier())
- .build()
- def response = null
- try {
- response = client.execute(post)
- } catch (Exception e) {
- log.error("[${issue.key}] Failed to notify ABS server. Error: ${e.message}")
- }
- client.close()
- def statusCode = response?.statusLine?.statusCode
- result += response.toString() + LINE
- } else log.error "File [" + path + "] not exist"
- }
- def json = JsonOutput.toJson(savedAttachments)
- result += json + LINE
- setProperty(ips, user, issue, ATTACHMENT_PROPERTY_KEY, json)
- } else {
- log.error("Page id not stored")
- }
- private String convertResponseStreamToString(java.io.InputStream is) {
- if (is == null) return ""
- java.util.Scanner s = new java.util.Scanner(is)
- s.useDelimiter("\\A")
- String streamString = s.hasNext() ? s.next() : ""
- s.close()
- return streamString
- }
- private String getProperty(IssuePropertyService ips, ApplicationUser user, Issue issue, String property) {
- return ips.getProperty(user, issue.id, property).getEntityProperty().getOrNull()?.value
- }
- private boolean setProperty(IssuePropertyService ips, ApplicationUser user, Issue issue, String property, String value) {
- def validation = ips.validateSetProperty(user, issue.id, new EntityPropertyService.PropertyInput(value, property))
- if (validation.valid) {
- ips.setProperty(user, validation)
- log.error("Stored page id " + value + " to issue property " + property)
- return true
- } else {
- log.error("Failed to store page id " + value + " to issue property " + property + ": " + validation.errorCollection)
- return false
- }
- }
- return result
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement