본문 바로가기

ALM/Jira

07. Workflow PostFunc

이번에는 생성한 이슈타입에 할당한 Customized 된 Workflow 에
 
후처리 함수를 등록하는 방법에 대해 알아보자.
 
 
 
Interface
 
먼저 아래와 같이 Jira settings -> Issues -> Workflows 메뉴로 들어간다.
 
 
그러면 아래와 같이 생성한 이슈와 연결된 Workflow 가 나타나는데 Edit 버튼을 눌러 해당 Workflow 로 들어간다.
 
 
그리고 후처리 함수가 실행될 Workflow 의 Transition 을 선택한다.
 
 
그리고 Add post function 버튼을 눌러 스크립트를 추가한 화면이다.
 
 
 
Script
 
스크립트 러너에 작성되는 스크립트는 보통 외부 시스템과 통신하기 위해 사용되는데
 
이중 먼저 Condition 항목으로 특정 조건에서만 해당 post function 이 동작하도록 할 수 있다.
 
 
그리고 Code 부분에 Condition 이 통과 되었을 때 실행할 코드를 넣으면 된다.
 
 
 
Sample 
 
아래는 CloudBees Flow 와 연동하기 위해 사용한 코드들이다.
 
 
Run Condition
 
((Map) issue.fields.issuetype)?.name == 'EFDevelopment'
 
Run Script
 
import javax.net.ssl.*
import java.security.cert.X509Certificate
import java.security.cert.CertificateException
 
def sslIgnore() {
    def trustAllCerts = [
        new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return null
            }
 
            public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {
            }
 
            public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {
            }
        }
    ] as TrustManager[]
    
    def nullHostnameVerifier = [
            verify: { hostname, session -> true }
    ] as HostnameVerifier
 
    SSLContext sc = SSLContext.getInstance("SSL")
    sc.init(null, trustAllCerts, new java.security.SecureRandom())
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory())
    HttpsURLConnection.setDefaultHostnameVerifier(nullHostnameVerifier)
 
    Authenticator.setDefault (new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication ("admin", "changeme".toCharArray());
        }
    });
}
 
HttpURLConnection sendGetRequest(String request)
{
    URL url = new URL(request);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();   
    
    connection.setRequestMethod("GET");    
    connection.setUseCaches(false);  
    connection.setConnectTimeout(5000);
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
    connection.connect();
    
    return connection;
}
 
HttpURLConnection sendPostRequest(String request, String params)
{
    byte[] postData = params.getBytes("UTF-8");
    int postDataLength = postData.length;
    
    URL url = new URL(request);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();   
    
    connection.setRequestMethod("POST");    
    connection.setConnectTimeout(5000);
    connection.setUseCaches(false);  
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
    connection.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
    DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
    wr.write( postData );
    connection.connect();
    
    return connection;
}
 
def getProcedure (String serverName) {
    HttpURLConnection connection = sendGetRequest("https://${serverName}/rest/v1.0/projects");
 
    if (connection.responseCode == 200 || connection.responseCode == 201) {
       BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
       StringBuilder sb = new StringBuilder();
       String line;
       while ((line = br.readLine()) != null) {
           sb.append(line+"\n");
       }
       br.close();
       connection.disconnect();
       return sb.toString();
    } else {
        connection.disconnect();
        return "Failed"
    }
}
 
def runProcedure (String serverName, String projectName, String procedureName, String acutalParams=null) {
    if(acutalParams == null ||acutalParams == "") {
        def params= "{\"projectName\": \"$projectName\", \"procedureName\": \"$procedureName\"}"
        HttpURLConnection connection = sendPostRequest("https://${serverName}/rest/v1.0/jobs?request=runProcedure",params);
        if (connection.responseCode == 200 || connection.responseCode == 201) {
            return "Success"
        } else {
            return "Fail"
        }
    } else {
        def params= "{ \"projectName\": \"$projectName\", \"procedureName\": \"$procedureName\", \"body\": { \"parameters\": { \"actualParameter\": [$acutalParams] } } }"
        
    
        HttpURLConnection connection = sendPostRequest("https://${serverName}/rest/v1.0/jobs?request=runProcedure",params);
        if (connection.responseCode == 200 || connection.responseCode == 201) {
            return "Success"
        } else {
            return "Fail"
        }    
    }
}
 
def issueKey = issue.key
def efProject = 'customfield_10033'
def efProcedure = 'customfield_10034'
def efServer = 'customfield_10036'
def efActual = 'customfield_10037'
def efProjectValue = ''
def efProcedureValue = ''
def efServerValue = ''
def efActualValue = ''
 
def result = post("/rest/api/2/issue/${issueKey}/comment")
        .header('Content-Type', 'application/json')
        .body([
            body: comment
        ])
        .asString()
 
result = get("/rest/api/2/issue/${issueKey}?fields=${efServer}")
        .header('Content-Type', 'application/json')
        .asObject(Map)
if (result.status == 200) {
    efServerValue = result.body.fields[efServer]
} else {
    return "Error retrieving issue ${result}"
}
 
result = get("/rest/api/2/issue/${issueKey}?fields=${efProject}")
        .header('Content-Type', 'application/json')
        .asObject(Map)
if (result.status == 200) {
    efProjectValue = result.body.fields[efProject]
} else {
    return "Error retrieving issue ${result}"
}
 
result = get("/rest/api/2/issue/${issueKey}?fields=${efProcedure}")
        .header('Content-Type', 'application/json')
        .asObject(Map)
if (result.status == 200) {
    efProcedureValue = result.body.fields[efProcedure]
} else {
    return "Error retrieving issue ${result}"
}
 
result = get("/rest/api/2/issue/${issueKey}?fields=${efActual}")
        .header('Content-Type', 'application/json')
        .asObject(Map)
if (result.status == 200) {
    efActualValue = result.body.fields[efActual]
} else {
    return "Error retrieving issue ${result}"
}
 
sslIgnore();
 
runProcedure("${efServerValue}","${efProjectValue}","${efProcedureValue}");
 
 
 
 
 
 

'ALM > Jira' 카테고리의 다른 글

06. Workflow Customization  (0) 2020.01.15
05. Field Customization  (0) 2020.01.15
04. Issue Type Customization  (0) 2020.01.15
03. Customization Overview  (0) 2020.01.15
02. Issue  (0) 2020.01.15