Groovy スクリプト例

このページの内容

お困りですか?

アトラシアン コミュニティをご利用ください。

コミュニティに質問

始めるための例をいくつかご紹介します。

自動化

オブジェクト属性の更新

import com.atlassian.jira.component.ComponentAccessor;
   
def objectFacade = ComponentAccessor.getOSGiComponentInstanceOfType(ComponentAccessor.getPluginAccessor().getClassLoader().findClass("com.riadalabs.jira.plugins.insight.channel.external.api.facade.ObjectFacade"));
def objectTypeAttributeFacade = ComponentAccessor.getOSGiComponentInstanceOfType(ComponentAccessor.getPluginAccessor().getClassLoader().findClass("com.riadalabs.jira.plugins.insight.channel.external.api.facade.ObjectTypeAttributeFacade"));
def objectAttributeBeanFactory = ComponentAccessor.getOSGiComponentInstanceOfType(ComponentAccessor.getPluginAccessor().getClassLoader().findClass("com.riadalabs.jira.plugins.insight.services.model.factory.ObjectAttributeBeanFactory"));
  
def objectTypeAttributeBean = objectTypeAttributeFacade.loadObjectTypeAttributeBean(3333).createMutable() //The id of the attribute
  
  /* Create the new attribute bean based on the value */
        def newObjectAttributeBean = objectAttributeBeanFactory.createObjectAttributeBeanForObject(object, objectTypeAttributeBean, "The Value");
        /* Load the attribute bean */
        def objectAttributeBean = objectFacade.loadObjectAttributeBean(object.getId(), objectTypeAttributeBean.getId());
        if (objectAttributeBean != null) {
           /* If attribute exist reuse the old id for the new attribute */
           newObjectAttributeBean.setId(objectAttributeBean.getId());
        }
/* Store the object attribute into Insight. */
try {
    objectTypeAttributeBean = objectFacade.storeObjectAttributeBean(newObjectAttributeBean);
} catch (Exception vie) {
    log.warn("Could not update object attribute due to validation exception:" + vie.getMessage());
}

このページの内容

条件

Insight カスタム フィールド値の制御

import com.atlassian.jira.component.ComponentAccessor;
import com.atlassian.jira.issue.fields.CustomField;
 
def value = issue.getCustomFieldValue(ComponentAccessor.getCustomFieldManager().getCustomFieldObject(10000)); // Change ID to the correct one     
 
/* If an insight custom field has an object called "Microsoft" it will fail */
if (value != null && "Microsoft".equals(value[0].getName())) {
    return false;
}
 
return true;

バリデーター

Insight カスタム フィールドの検証

import com.atlassian.jira.component.ComponentAccessor;
import com.atlassian.jira.issue.fields.CustomField;
 
def value = issue.getCustomFieldValue(ComponentAccessor.getCustomFieldManager().getCustomFieldObject(10000)); // Change ID to the correct one     
 
/* If an insight custom field has an object called "Microsoft" it will fail */
if (value != null && "Microsoft".equals(value[0].getName())) {
    return "This is not a valid vendor!";
}
return true

事後操作

キーによるオブジェクトの読み込み

指定したオブジェクト キーの Insight オブジェクトを読み込む簡単な例:

import com.atlassian.jira.component.ComponentAccessor;
 
/* The object facade class */
Class objectFacadeClass = ComponentAccessor.getPluginAccessor().getClassLoader().findClass("com.riadalabs.jira.plugins.insight.channel.external.api.facade.ObjectFacade"); 
 
/* The reference to the object facade which you can use in your code */
def objectFacade = ComponentAccessor.getOSGiComponentInstanceOfType(objectFacadeClass);
 
/* Log the Insight object */
log.info("Insight object of key SCH-1: " + objectFacade.loadObjectBean("SCH-1"));
 
return true;


オブジェクトを作成する

Jira 課題でフィールドの値を使ってオブジェクトを作成する方法の例を示します。通常は、ワークフローのどこかのトランジションで実行します。作成するオブジェクトのタイプは「Customer」、名前は課題の要約、オブジェクトの優先度は課題の優先度、オブジェクトの説明は課題の説明とします。

オブジェクト タイプの設定は次のようになります。

これは次のようになります。

import com.atlassian.jira.component.ComponentAccessor;
import java.util.ArrayList;
   
/* Get Insight Object Facade from plugin accessor */
Class objectFacadeClass = ComponentAccessor.getPluginAccessor().getClassLoader().findClass("com.riadalabs.jira.plugins.insight.channel.external.api.facade.ObjectFacade"); 
def objectFacade = ComponentAccessor.getOSGiComponentInstanceOfType(objectFacadeClass);
  
/* Get Insight Object Type Facade from plugin accessor */
Class objectTypeFacadeClass = ComponentAccessor.getPluginAccessor().getClassLoader().findClass("com.riadalabs.jira.plugins.insight.channel.external.api.facade.ObjectTypeFacade"); 
def objectTypeFacade = ComponentAccessor.getOSGiComponentInstanceOfType(objectTypeFacadeClass);
  
/* Get Insight Object Attribute Facade from plugin accessor */
Class objectTypeAttributeFacadeClass = ComponentAccessor.getPluginAccessor().getClassLoader().findClass("com.riadalabs.jira.plugins.insight.channel.external.api.facade.ObjectTypeAttributeFacade"); 
def objectTypeAttributeFacade = ComponentAccessor.getOSGiComponentInstanceOfType(objectTypeAttributeFacadeClass);
  
Class objectAttributeBeanFactoryClass = ComponentAccessor.getPluginAccessor().getClassLoader().findClass("com.riadalabs.jira.plugins.insight.services.model.factory.ObjectAttributeBeanFactory"); 
def objectAttributeBeanFactory = ComponentAccessor.getOSGiComponentInstanceOfType(objectAttributeBeanFactoryClass);
 
/* The ID of the object type "Customer" is 1 in this example. The easiest way of finding the ID of an object type is to click at the object type in the object type tree and open up the web browser console to get the id that Insight uses to fetch objects. This will be easier to do in upcoming releases. */
def objectTypeCustomer = objectTypeFacade.loadObjectTypeBean(1);
   
/* Create a new unsaved object bean */
def newObjectBean = objectTypeCustomer.createMutableObjectBean();
   
 
/* Set up the attribute list */
def objectAttributeBeans = new ArrayList();
   
/* Set the name of the customer */
def nameObjectTypeAttributeBean = objectTypeAttributeFacade.loadObjectTypeAttributeBean(1);   // 1 is the ID of the object type attribute "Name"
objectAttributeBeans.add(objectAttributeBeanFactory.createObjectAttributeBeanForObject(newObjectBean, nameObjectTypeAttributeBean, issue.getSummary()));
 
 
/* Set the priority of the customer */
if (issue.getPriorityObject() != null) {
    def priorityObjectTypeAttributeBean = objectTypeAttributeFacade.loadObjectTypeAttributeBean(2);   // 2 is the ID of the object type attribute "Priority"
    objectAttributeBeans.add(objectAttributeBeanFactory.createObjectAttributeBeanForObject(newObjectBean, priorityObjectTypeAttributeBean, issue.getPriorityObject().getName()));
}
  
 /* Set the description of the customer */
if (issue.getDescription() != null && !issue.getDescription().equals("")) {
    def descriptionObjectTypeAttributeBean = objectTypeAttributeFacade.loadObjectTypeAttributeBean(3);   // 3 is the ID of the object type attribute "Description"
    objectAttributeBeans.add(objectAttributeBeanFactory.createObjectAttributeBeanForObject(newObjectBean, descriptionObjectTypeAttributeBean, issue.getDescription()));
}
  
 /* Set all object attributes to the object */
newObjectBean.setObjectAttributeBeans(objectAttributeBeans);
   
/* Store the object into Insight. The new ObjectBean will be updated with an unique ID */
try {
    newObjectBean = objectFacade.storeObjectBean(newObjectBean);
    log.warn("newObjectBean: " + newObjectBean);
} catch (Exception vie) {
    log.warn("Could not create issue due to validation exception:" + vie.getMessage());
}
  
/* Done! :) */
return true;

製品カタログ注文からメールを送信する

これは、Jira Service Desk カスタマー ポータルで注文したときに、外部のサプライヤー/ベンダーにメールを送信する方法の詳しい例です。

例を表示...
import com.atlassian.jira.component.ComponentAccessor;
import com.atlassian.mail.server.MailServerManager;
import com.atlassian.mail.server.SMTPMailServer;
import com.atlassian.jira.mail.Email;
import com.atlassian.mail.queue.SingleMailQueueItem;
import com.atlassian.jira.issue.CustomFieldManager;
import com.atlassian.jira.issue.fields.CustomField;
import com.atlassian.jira.issue.IssueManager;
import com.atlassian.jira.issue.Issue;
import com.atlassian.jira.issue.MutableIssue;
import com.atlassian.jira.event.type.EventDispatchOption;
import org.joda.time.DateTime;
import java.util.Locale;
 
MailServerManager mailServerManager = ComponentAccessor.getMailServerManager();
SMTPMailServer mailServer = mailServerManager.getDefaultSMTPMailServer();
 
if (mailServer == null) {
    log.error("No email smtp server configured, abort");
    return;
}
 
CustomField invoiceAddressCF = ComponentAccessor.getCustomFieldManager().getCustomFieldObject(10914);   // The ID of custom fields can be found in JIRA Admin.
CustomField invoiceContactCF = ComponentAccessor.getCustomFieldManager().getCustomFieldObject(11012);   // The ID of custom fields can be found in JIRA Admin.
CustomField deliveryAddressCF = ComponentAccessor.getCustomFieldManager().getCustomFieldObject(10915);  // The ID of custom fields can be found in JIRA Admin.
CustomField deliveryContactCF = ComponentAccessor.getCustomFieldManager().getCustomFieldObject(11013);  // The ID of custom fields can be found in JIRA Admin.
CustomField costCenterCF = ComponentAccessor.getCustomFieldManager().getCustomFieldObject(11200);       // The ID of custom fields can be found in JIRA Admin.
 
CustomField desktopCF = ComponentAccessor.getCustomFieldManager().getCustomFieldObject(10906);          // The ID of custom fields can be found in JIRA Admin.
CustomField laptopCF = ComponentAccessor.getCustomFieldManager().getCustomFieldObject(11000);           // The ID of custom fields can be found in JIRA Admin.
CustomField printerCF = ComponentAccessor.getCustomFieldManager().getCustomFieldObject(10909);          // The ID of custom fields can be found in JIRA Admin.
 
// Count of above fields
CustomField normalCountCF = ComponentAccessor.getCustomFieldManager().getCustomFieldObject(11413);      // The ID of custom fields can be found in JIRA Admin.
 
 
// Accessories
CustomField accessories1CF = ComponentAccessor.getCustomFieldManager().getCustomFieldObject(11401);     // The ID of custom fields can be found in JIRA Admin.
CustomField accessories2CF = ComponentAccessor.getCustomFieldManager().getCustomFieldObject(11402);     // The ID of custom fields can be found in JIRA Admin.
CustomField accessories3CF = ComponentAccessor.getCustomFieldManager().getCustomFieldObject(11403);     // The ID of custom fields can be found in JIRA Admin.
 
// Accessories count
CustomField countAccessories1CF = ComponentAccessor.getCustomFieldManager().getCustomFieldObject(11407);
CustomField countAccessories2CF = ComponentAccessor.getCustomFieldManager().getCustomFieldObject(11408);
CustomField countAccessories3CF = ComponentAccessor.getCustomFieldManager().getCustomFieldObject(11409);
 
 
def invoiceAddressValue = invoiceAddressCF.getValue(issue);
def invoiceContactValue = invoiceContactCF.getValue(issue);
def deliveryAddressValue = deliveryAddressCF.getValue(issue);
def deliveryContactValue = deliveryContactCF.getValue(issue);
def costCenterValue = costCenterCF.getValue(issue);
 
def invoiceAddressObjectBean = invoiceAddressValue[0];
def deliveryAddressObjectBean = deliveryAddressValue[0];
 
def emailbody;
 
Map<String, Object> emailMap = new HashMap<String, Object>();
emailMap.put("invoiceContact", invoiceContactValue);
 
 
/* Get Insight Object Facade from plugin accessor */
Class objectFacadeClass = ComponentAccessor.getPluginAccessor().getClassLoader().findClass("com.riadalabs.jira.plugins.insight.channel.external.api.facade.ObjectFacade");  
def objectFacade = ComponentAccessor.getOSGiComponentInstanceOfType(objectFacadeClass);
 
 
/* Get Insight Object Attribute Facade from plugin accessor */
Class objectTypeAttributeFacadeClass = ComponentAccessor.getPluginAccessor().getClassLoader().findClass("com.riadalabs.jira.plugins.insight.channel.external.api.facade.ObjectTypeAttributeFacade");  
def objectTypeAttributeFacade = ComponentAccessor.getOSGiComponentInstanceOfType(objectTypeAttributeFacadeClass);
 
 
/* 9 is the ID of the object type attribute for invoice name */
def invoiceName = objectFacade.loadObjectAttributeBean(invoiceAddressObjectBean.getId(), 9).getObjectAttributeValueBeans()[0];   
emailMap.put("invoiceName", invoiceName.getValue());
 
 
/* 12 is the ID of the object type attribute for invoice postal address */
def invoicePostalAddress = objectFacade.loadObjectAttributeBean(invoiceAddressObjectBean.getId(), 12).getObjectAttributeValueBeans()[0];
emailMap.put("invoicePostalAddress", invoicePostalAddress.getValue());
 
 
/* 35 is the ID of the object type attribute for invoice postal number */
def invoicePostalNumber = objectFacade.loadObjectAttributeBean(invoiceAddressObjectBean.getId(), 35).getObjectAttributeValueBeans()[0];
emailMap.put("invoicePostalNumber", invoicePostalNumber.getValue());
 
 
/* 13 is the ID of the object type attribute for invoice city */
def invoiceCity = objectFacade.loadObjectAttributeBean(invoiceAddressObjectBean.getId(), 13).getObjectAttributeValueBeans()[0];
emailMap.put("invoiceCity", invoiceCity.getValue());
 
emailMap.put("orderDate", new DateTime(new Date()).toString("yyyy-MM-dd", Locale.getDefault()));
emailMap.put("orderNumber", issue.getKey());
emailMap.put("costCenter", costCenterValue);
 
def productObjectList = desktopCF.getValue(issue);
if (productObjectList == null) {
    productObjectList = laptopCF.getValue(issue);
}
if (productObjectList == null) {
    productObjectList = printerCF.getValue(issue);
}
 
def configItem = false;
if (productObjectList != null) {
    productObjectList.each{productObject ->
        def attributes = productObject.getObjectAttributeBeans();                       
        attributes.each{attribute ->
            def type;
            try {
                type = objectTypeAttributeFacade.loadObjectTypeAttributeBean(attribute.getObjectTypeAttributeId());
            } catch (Exception ee) {}
             
            /** Configuration Item attribute tells us if the selected object should be sent 
              * to company for configuration before shipped to customer */
            if (type != null && "Configuration Item".equals(type.getName())) {
                configItem = attribute.getObjectAttributeValueBeans()[0].getValue();
            }
        }
    }
}
 
List<Map> products = new ArrayList<Map>();
float totalPrice = 0;
 
if (configItem) {
    /* If the selected object should be sent to company for configuration before shipped to customer */
    emailMap.put("deliveryContact", "IT Department => " + deliveryContactValue);
 
    /* Set delivery address to specific Company Center defined in Insight, in this case OBJECT-28 */
    def configDeliveryAddressObjectBean = objectFacade.loadObjectBean("OBJECT-28");
    def deliveryName = objectFacade.loadObjectAttributeBean(configDeliveryAddressObjectBean.getId(), 8).getObjectAttributeValueBeans()[0];
    emailMap.put("deliveryName", deliveryName.getValue());
 
    def deliveryPostAddress = objectFacade.loadObjectAttributeBean(configDeliveryAddressObjectBean.getId(), 10).getObjectAttributeValueBeans()[0];
    emailMap.put("deliveryPostAddress", deliveryPostAddress.getValue());
 
    def deliveryPostNumber = objectFacade.loadObjectAttributeBean(configDeliveryAddressObjectBean.getId(), 36).getObjectAttributeValueBeans()[0];
    emailMap.put("deliveryPostNumber", deliveryPostNumber.getValue());
 
    def deliveryCity = objectFacade.loadObjectAttributeBean(configDeliveryAddressObjectBean.getId(), 11).getObjectAttributeValueBeans()[0];
    emailMap.put("deliveryCity", deliveryCity.getValue());
 
    int count = getOptionValue(normalCountCF.getValue(issue));
 
    productObjectList.each{productObject ->
        Map productValues = getProductValue(count, productObject, objectFacade, objectTypeAttributeFacade);
        totalPrice += Float.parseFloat(productValues.get("4"));
        products.add(productValues);
    }
 
    emailMap.put("products", products);
    emailMap.put("totalPrice", String.format("%.2f", totalPrice));
    sendMail(emailMap, issue);
    products.clear();
    totalPrice = 0;
 
} else {
 
    products = new ArrayList<Map>();
    totalPrice = 0;
 
    if (productObjectList != null) {
        int count = getOptionValue(normalCountCF.getValue(issue));
 
        productObjectList.each{productObject ->
            Map productValues = getProductValue(count, productObject, objectFacade, objectTypeAttributeFacade);
            totalPrice += Float.parseFloat(productValues.get("4"));
            products.add(productValues);
        }
    }
}
 
emailMap.put("deliveryContact", deliveryContactValue);
 
// Set delivery details
def deliveryName = objectFacade.loadObjectAttributeBean(deliveryAddressObjectBean.getId(), 8).getObjectAttributeValueBeans()[0];
emailMap.put("deliveryName", deliveryName.getValue());
 
def deliveryPostAddress = objectFacade.loadObjectAttributeBean(deliveryAddressObjectBean.getId(), 10).getObjectAttributeValueBeans()[0];
emailMap.put("deliveryPostAddress", deliveryPostAddress.getValue());
 
def deliveryPostNumber = objectFacade.loadObjectAttributeBean(deliveryAddressObjectBean.getId(), 36).getObjectAttributeValueBeans()[0];
emailMap.put("deliveryPostNumber", deliveryPostNumber.getValue());
 
def deliveryCity = objectFacade.loadObjectAttributeBean(deliveryAddressObjectBean.getId(), 11).getObjectAttributeValueBeans()[0];
emailMap.put("deliveryCity", deliveryCity.getValue());
 
def accessoriesList = accessories1CF.getValue(issue);
 
if (accessoriesList != null) {
    int count = getOptionValue(countAccessories1CF.getValue(issue));
 
    accessoriesList.each{accObject ->
        Map productValues = getProductValue(count, accObject, objectFacade, objectTypeAttributeFacade);
        totalPrice += Float.parseFloat(productValues.get("4"));
        products.add(productValues);
    }  
}
 
accessoriesList = accessories2CF.getValue(issue);
if (accessoriesList != null) {
    int count = getOptionValue(countAccessories2CF.getValue(issue));
 
    accessoriesList.each{accObject ->
        Map productValues = getProductValue(count, accObject, objectFacade, objectTypeAttributeFacade);
        totalPrice += Float.parseFloat(productValues.get("4"));
        products.add(productValues);
    }  
}
 
accessoriesList = accessories3CF.getValue(issue);
if (accessoriesList != null) {
    int count = getOptionValue(countAccessories3CF.getValue(issue));
 
    accessoriesList.each{accObject ->
        Map productValues = getProductValue(count, accObject, objectFacade, objectTypeAttributeFacade);
        totalPrice += Float.parseFloat(productValues.get("4"));
        products.add(productValues);
    }  
}
 
emailMap.put("products", products);
emailMap.put("totalPrice", String.format("%.2f", totalPrice));
 
if (!products.isEmpty()) {
    sendMail(emailMap, issue);
}
 
return true;
 
/* Set order type on ticket to let agent to now if this has been sent to supplier/vendor */
def agent = ComponentAccessor.getJiraAuthenticationContext().getLoggedInUser();
CustomField orderTypeCF = ComponentAccessor.getCustomFieldManager().getCustomFieldObject(11414);   // JIRA Text custom field
MutableIssue mi = (MutableIssue) issue;
mi.setCustomFieldValue(orderTypeCF, "Supplier Order");
ComponentAccessor.getIssueManager().updateIssue(agent, mi, EventDispatchOption.DO_NOT_DISPATCH, false);
 
/* Script internal methods */
void sendMail(Map<String, Object> emailMap, Issue issue) {
     
    /** The invoice html email template is stored on server */
    def emailbody = ComponentAccessor.getVelocityManager().getBody("/scripts/", "invoice.html", emailMap);
    try {
     
        /** Email address to supplier */
        Email email = new Email("order@example.com");
         
        /** Copy a mail to the agent */
        email.setCc(agent.getEmailAddress());
 
        /** Uncomment this if you want a specific email adress as the sender and not JIRA default */
        // email.setFrom("servicedesk@company.com");   
 
        email.setSubject("Company WebShop, order number: " + issue.getKey());
        email.setMimeType("text/html");
        email.setBody(emailbody);
 
        SingleMailQueueItem item = new SingleMailQueueItem(email);
        ComponentAccessor.getMailQueue().addItem(item);
 
    } catch (Exception ee) {
        log.error("Error sending mail to: " + emailAddress, ee);
    }
}
 
/* 
 * This method is to setup the rows in the email with all products and pricing. The method returns a MAP with this keys:
 * 0: Count 
 * 1: Product number
 * 2: Product Name
 * 3: Price
 * 4: Total price
 */
Map getProductValue(int count, Object insightObject, Object objectFacade, Object objectTypeAttributeFacade) {
    Map productValues = new HashMap<String, String>();
 
    productValues.put("0", String.valueOf(count));
    productValues.put("2", insightObject.getName());
 
    String price;
 
    def attributes = objectFacade.findObjectAttributeBeans(insightObject.getId());                       
    attributes.each{attribute ->
        def typeName = objectTypeAttributeFacade.loadObjectTypeAttributeBean(attribute.getObjectTypeAttributeId()).getName();
 
        if ("Price".equals(typeName)) {
            price = attribute.getObjectAttributeValueBeans()[0].getValue();
 
            productValues.put("3", String.format("%.2f", Float.valueOf(price)));
        } else if ("Product number".equals(typeName)) {
            productValues.put("1", attribute.getObjectAttributeValueBeans()[0].getValue());
        }
    }
 
    float productPrice = count * Float.parseFloat(price);
    productValues.put("4", String.format("%.2f", productPrice));                 
    return productValues;
}
 
/* Get the number value from an option of a JIRA Select Custom Field with options like (1, 2, 3, 4.... ) */
int getOptionValue(Object option) {
    try {
        if (option != null) {
            return Integer.parseInt(option.getValue());
        }
    } catch (Exception ee) {
    }
    return 1;
}
invoice.html の例を表示...
<!DOCTYPE html>
<html>
<head>
    <style>
        div.h1 {
            border-bottom: 1px solid #000;
            width: 100%;
        }
 
        h1 {
            margin: 0px;
            padding: 0px;
        }
 
        th {
            text-align: left;
        }
    </style>
</head>
<body>
<div class="h1">
    <h1>Webshop - Confirmation</h1>
</div>
<h3>Invoice Address</h3>
<div>Company name: <b>$invoiceName</b></div>
#if($invoiceContact)
<div>Contact: <b>$invoiceContact</b></div>
#end
<div>Postal Address: <b>$invoicePostalAddress</b></div>
<div>Postcode & City: <b>$invoicePostalNumber $invoiceCity</b></div>
 
<h3>Delivery Address</h3>
<div>Company Name: <b>$deliveryContact</b></div>
#if($deliveryContact)
<div>Contact: <b>$deliveryContact</b></div>
#end
<div>Postal Address: <b>$deliveryPostAddress</b></div>
<div>Postcode & City: <b>$deliveryPostAddress $deliveryCity</b></div>
 
<h3>Order Information</h3>
<div>Order Date: <b>$orderDate</b></div>
<div>Order Nr: <b>$orderNumber</b></div>
<div>Cost Center: <b>$costCenter</b></div>
 
<h3>Order Specification</h3>
<table cellspacing="2" cellpadding="2">
    <tr>
        <th>Count</th>
        <th>Product nr</th>
        <th>Product name</th>
        <th>Unit Price</th>
        <th>Total Price</th>
    </tr>
    #foreach ($product in $products)
    <tr>
        <td>$product.get("0")</td>
        <td>$product.get("1")</td>
        <td>$product.get("2")</td>
        <td>$product.get("3") kr</td>
        <td>$product.get("4") kr</td>
    </tr>
    #end
    <tr>
        <td colspan=5 style="padding-top: 10px;">
            <b>Total without VAT: $totalPrice kr</b>
        </td>
    </tr>
</table>
 
</body>
</html>

オブジェクト属性の更新

これは特定のオブジェクト属性を更新する方法の例です。

オブジェクト タイプの設定は次のようになります。

これは次のようになります。

import com.atlassian.jira.component.ComponentAccessor;
import com.atlassian.jira.issue.fields.CustomField;
   
/* Get Insight Object Facade from plugin accessor */
Class objectFacadeClass = ComponentAccessor.getPluginAccessor().getClassLoader().findClass("com.riadalabs.jira.plugins.insight.channel.external.api.facade.ObjectFacade");  
def objectFacade = ComponentAccessor.getOSGiComponentInstanceOfType(objectFacadeClass);
 
/* Get Insight Object Attribute Facade from plugin accessor */
Class objectTypeAttributeFacadeClass = ComponentAccessor.getPluginAccessor().getClassLoader().findClass("com.riadalabs.jira.plugins.insight.channel.external.api.facade.ObjectTypeAttributeFacade"); 
def objectTypeAttributeFacade = ComponentAccessor.getOSGiComponentInstanceOfType(objectTypeAttributeFacadeClass);
 
 
/* Get the factory that creates Insight Attributes */
Class objectAttributeBeanFactoryClass = ComponentAccessor.getPluginAccessor().getClassLoader().findClass("com.riadalabs.jira.plugins.insight.services.model.factory.ObjectAttributeBeanFactory");
def objectAttributeBeanFactory = ComponentAccessor.getOSGiComponentInstanceOfType(objectAttributeBeanFactoryClass);
 
/* This is the custom field with the value you want to add to an object attribute */
CustomField jiraCustomField = ComponentAccessor.getCustomFieldManager().getCustomFieldObject(12345);   // Change 12345 to the correct value
 
/* This is the custom field where the object/s you want to set the value */
CustomField insightCustomField = ComponentAccessor.getCustomFieldManager().getCustomFieldObject(23456);   // Change 23456 to the correct value
def insightObjects = issue.getCustomFieldValue(insightCustomField);   // "issue" variable is always accessible in post function scripts.
 
/* This is the priority object type attribute and the one we want to modify */
def objectTypeAttributeBean = objectTypeAttributeFacade.loadObjectTypeAttributeBean(8799);
 
if (insightObjects != null) {
    insightObjects.each{insightObject ->
        /* Create the new attribute bean based on the value */
        def newValue = issue.getCustomFieldValue(jiraCustomField);
        def newObjectAttributeBean = objectAttributeBeanFactory.createObjectAttributeBeanForObject(insightObject, objectTypeAttributeBean, newValue[0].getName());
        /* Load the attribute bean */
        def objectAttributeBean = objectFacade.loadObjectAttributeBean(insightObject.getId(), objectTypeAttributeBean.getId());
        if (objectAttributeBean != null) {
           /* If attribute exist reuse the old id for the new attribute */
           newObjectAttributeBean.setId(objectAttributeBean.getId());
        }
        /* Store the object attribute into Insight. */
        try {
            objectAttributeBean = objectFacade.storeObjectAttributeBean(newObjectAttributeBean);
        } catch (Exception vie) {
            log.warn("Could not update object attribute due to validation exception:" + vie.getMessage());
        }
    }
}
 
 
 
/* Done! :) */
return true;
  

Insight カスタム フィールドの更新

これは、Insight カスタム フィールド (id=10001) をオブジェクトで更新する方法の詳しい例です。ここで、名前属性は、テキスト カスタム フィールド (id=10000) で示されたテキスト文字列と一致します。

import com.atlassian.jira.component.ComponentAccessor;
import com.atlassian.jira.issue.fields.CustomField;
import com.atlassian.jira.issue.Issue;
import com.atlassian.jira.issue.MutableIssue;
import com.atlassian.jira.event.type.EventDispatchOption;
 
 
/* Custom field with the value to filter on */
CustomField valueCF = ComponentAccessor.getCustomFieldManager().getCustomFieldObject(10000);        
 
if (valueCF == null || valueCF.getValue(issue) == null) {
    return true;
}
 
/* Insight custom field to set */
CustomField insightCF = ComponentAccessor.getCustomFieldManager().getCustomFieldObject(10001);       
 
if (insightCF == null) {
    return true;
}
 
/* Get Insight IQL Facade from plugin accessor */
Class iqlFacadeClass = ComponentAccessor.getPluginAccessor().getClassLoader().findClass("com.riadalabs.jira.plugins.insight.channel.external.api.facade.IQLFacade"); 
def iqlFacade = ComponentAccessor.getOSGiComponentInstanceOfType(iqlFacadeClass);
 
/* Specify the schema id as well as the IQL that will fetch objects. In this case all objects with Name matching the valueCF, be sure to include " around value */
def objects = iqlFacade.findObjectsByIQLAndSchema(1, "Name = \"" + valueCF.getValue(issue) + "\"");
if (!objects.isEmpty()) {
   MutableIssue mi = (MutableIssue) issue;
    mi.setCustomFieldValue(insightCF, objects);
    ComponentAccessor.getIssueManager().updateIssue(currentUser, mi, EventDispatchOption.DO_NOT_DISPATCH, false);
}
return true;

属性値によるオブジェクトの読み込み

指定したオブジェクト キーの Insight オブジェクトを読み込む簡単な例:

import com.atlassian.jira.component.ComponentAccessor;
 
/* Get Insight IQL Facade from plugin accessor */
Class iqlFacadeClass = ComponentAccessor.getPluginAccessor().getClassLoader().findClass("com.riadalabs.jira.plugins.insight.channel.external.api.facade.IQLFacade"); 
def iqlFacade = ComponentAccessor.getOSGiComponentInstanceOfType(iqlFacadeClass);
 
/* Specify the schema id as well as the IQL that will fetch objects. In this case all objects with Name matching the valueCF, be sure to include " around value */
def objects = iqlFacade.findObjectsByIQLAndSchema(1, "\"The attribute\" = \"" + attribute value + "\""); // See the complete list of possible IQL on the Insight Query Language documentation page
/* If this is a mandatory field you should be able to do this: */
log.info("Insight object: " + objects[0]);
 
return true;


報告者の組織への Insight カスタム フィールド値の設定

課題の報告者となる組織に Insight カスタム フィールドを設定します。以下はそのためのスクリプトです。事後操作は、作成トランジションに設定する際、事後操作リストの最後に必ず加えてください (課題の実際の作成後)。

import com.atlassian.jira.component.ComponentAccessor;
import com.atlassian.jira.issue.fields.CustomField;
import com.atlassian.jira.issue.Issue;
import com.atlassian.jira.issue.MutableIssue;
import com.atlassian.jira.event.type.EventDispatchOption;
import com.atlassian.jira.issue.context.IssueContextImpl;
import com.atlassian.jira.issue.fields.config.FieldConfig;
 
 
/* Custom field for the organisation */
CustomField organisationCF = ComponentAccessor.getCustomFieldManager().getCustomFieldObject(10000);        
 
if (organisationCF == null || organisationCF.getValue(issue) == null) {
    return false;
}
 
  
/* Get Insight Object Facade from plugin accessor */
Class objectFacadeClass = ComponentAccessor.getPluginAccessor().getClassLoader().findClass("com.riadalabs.jira.plugins.insight.channel.external.api.facade.ObjectFacade");  
def objectFacade = ComponentAccessor.getOSGiComponentInstanceOfType(objectFacadeClass);
 
  
Class customFieldFacadeClass = ComponentAccessor.getPluginAccessor().getClassLoader().findClass("com.riadalabs.jira.plugins.insight.services.core.CustomFieldService");  
def customFieldFacade = ComponentAccessor.getOSGiComponentInstanceOfType(customFieldFacadeClass);
 
IssueContextImpl issueContext = new IssueContextImpl(issue.getProjectObject(), issue.getIssueType());
FieldConfig fieldConfig = organisationCF.getRelevantConfig(issueContext);
 
def objectTypeAttributeName = null;
//objectTypeAttributeName = "JIRA User"  // Set an object type attribute name if you want to restrict the user fetch on just that type attribute.
 
def objects = customFieldFacade.findUserObjectsByNormalCustomField(
                                        fieldConfig.getId(), currentUser,
                                        objectTypeAttributeName,
                                        issue.getProjectObject().getId())
  
if (objects.isEmpty()) {
    return false;
}
  
def organisationTypeAttributeId = 123;  // The object type attribute id of the organisation attribute for the user object type.
def organisationObjectAttributeBean = objectFacade.loadObjectAttributeBean(objects[0].getId(), organisationTypeAttributeId);
if (organisationObjectAttributeBean == null) {
    return false;
}
  
MutableIssue mi = (MutableIssue) issue;
mi.setCustomFieldValue(organisationCF, [objectFacade.loadObjectBean(organisationObjectAttributeBean.getObjectAttributeValueBeans()[0].getReferencedObjectBeanId())]);
ComponentAccessor.getIssueManager().updateIssue(currentUser, mi, EventDispatchOption.DO_NOT_DISPATCH, false);
 
/* We are done! */
return true;

Insight カスタム フィールドで選択している Insight オブジェクトへのコメントの追加

トランジションのいくつかのステップで Insight オブジェクトにコメントを追加するとします。この方法の例を示します。

import com.atlassian.jira.component.ComponentAccessor;
import com.atlassian.jira.issue.fields.CustomField;
import com.atlassian.jira.issue.Issue;
import com.riadalabs.jira.plugins.insight.services.model.CommentBean;
/* Custom field for the organisation */
CustomField insightObjectCF = ComponentAccessor.getCustomFieldManager().getCustomFieldObject(10000);        
 
if (insightObjectCF == null || insightObjectCF.getValue(issue) == null) {
    return false;
}
 
/* Get Insight Object Facade from plugin accessor */
Class objectFacadeClass = ComponentAccessor.getPluginAccessor().getClassLoader().findClass("com.riadalabs.jira.plugins.insight.channel.external.api.facade.ObjectFacade");  
def objectFacade = ComponentAccessor.getOSGiComponentInstanceOfType(objectFacadeClass);
 
/* Make sure required in this example */
def objectBean = insightObjectCF.getValue(issue)[0];
  
CommentBean commentBean = new CommentBean();
commentBean.setComment("This is a comment");
commentBean.setRole(0);  // Public
commentBean.setAuthor(currentUser.getKey());
commentBean.setObjectId(objectBean.getId());
objectFacade.storeCommentBean(commentBean);
  
/* We are done! */
return true;

ログイン済みユーザーの設定

ログイン済みユーザーを設定する方法の例を示します。

import com.atlassian.jira.component.ComponentAccessor;
  
  
def authContext = ComponentAccessor.getJiraAuthenticationContext();
  
def currentUser = authContext.getLoggedInUser();
  
def userKeyToSet = “user123”; //Change to the actual User key
  
try {
  
    authContext.setLoggedInUser(ComponentAccessor.getUserManager().getUserByKey(userKeyToSet));
 
    /* Execution of code goes here */  
  
} finally {
  
    authContext.setLoggedInUser(currentUser);
  
}
Last modified on Mar 25, 2024

この内容はお役に立ちましたか?

はい
いいえ
この記事についてのフィードバックを送信する
Powered by Confluence and Scroll Viewport.