Post functions

On this page

Still need help?

The Atlassian Community is here for you.

Ask the community

Load object by key

Simple example to load an Insight object of a specified object key:

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;


Create object

This is an example of how you can create an object with values from fields in a JIRA Issue. This is typically executed in a transition somewhere in your workflow. The object we will create is of type "Customer" and we will create an object where the name is issue summary, the object priority is the issue priority and the object description is the issue description.

This is how the object type is setup:

This is how this could look like:

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;

Send email from a product catalog order

This is a more advanced example on how to send an email to the external supplier/vendor when a order is placed in the JIRA Service Desk customer portal:

Show example...
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;
}
Show example of 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>

Update object attribute

This is an example how you can update a specific object attributes

This is how the object type is setup:

This is how this could look like:

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;
  

Update Insight custom field

This is a more advanced example how to update an Insight Custom Field (id=10001) with Objects, where the Name Attribute matches the Text string indicated in a Text Custom Field (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;

Load object by attribute value

Simple example to load an Insight object of a specified object key:

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;


Set an Insight custom field value to the organization of the reporter

Let's say you want to set an Insight custom field to the organisation responsible for the reporter of the issue. This is the script to do that, and always remember to put the post function at the end of the list of post function when configuring it on the create transition (after the actual create of the issue)

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;

Add a comment to an Insight object selected in an Insight custom field

Let say you want to add a comment to an Insight object in some step of a transition. This is an example on how you can do that:

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;

Set a logged in user

This example shows how to set an logged in user

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 Sep 8, 2021

Was this helpful?

Yes
No
Provide feedback about this article
Powered by Confluence and Scroll Viewport.