Method Overview - Riada-AB/InsightManager GitHub Wiki
All methods in IM that are intended to be used by you has inline documentation specifying what imputs are expected and what can be expected in return. The inline documentation can either be read directly in the library or if if you are using Intellij you can highlight the method and press F1:
The examples below presumes that you have Setup IM and instantiated it as im.
Remember that IM is flexible, when a method requires an insight Object as an input parameter it will accept an object key, object ID or an objectBean.
/**
* A flexible method for returning an ObjectBean
* object can be ObjectBean/MutableObjectBean,Object Key (string) or object ID (int).
* Returns ObjectBean
*/
ObjectBean getObjectBean(def object)
A simple method for getting a single object. Great if you have the key or id already, or if you are not quite sure what you have, this will try and figure that out and return the corresponding ObjectBean.
/**
* Runs an IQL and returns matching objects
* schemaId What scheme to run the IQL on
* iql The IQL to be run
*
* return An array containing ObjectBeans
*/
ArrayList<ObjectBean> iql(int schemaId, String iql)
The IQL method expects the ID of schema you want to query and an IQL formated just like you would put it in the interface. Remember to put attribute values inside "" if they have spaces:
ArrayList<ObjectBean> employees = im.iql(1,"Name = \"Nisse Hult\"")
ArrayList<ObjectBean> departments = im.iql(1, "ObjectType = Departments")
/**
* Creates a new object with Attribute Values
* The label attribute must be populated (as an attribute)
* schemeId id of the scheme where you want to create your object
* objectTypeName Name of the object type you want to create
* AttributeValues A map containing the Attributes and values to be set.
* return The created ObjectBean
*/
ObjectBean createObject(int schemeId, String objectTypeName, Map AttributeValues)
This method expects an id of the scheme where the object should be created, the name of the objectType and Map containing the attributes and their values. Remember that you have to populate required attributes such as the label attribute for this to work.
/**
* Creates a new object with Attribute Values
* The label attribute must be populated (as an attribute)
* ObjectTypeId id of the objectType you want to create your object
* AttributeValues A map containing the Attributes and values to be set.
* return The created ObjectBean
*/
ObjectBean createObject(Integer ObjectTypeId, Map AttributeValues)
This is essentially the same as the one above, but useful if you already have the ObjectTypeId
//Create a new object with SchemeId 2 and ObjectTypeName Employee
ObjectBean newEmployee = im.createObject(2, "Employee", [Name: "Nisse Hult", Department: departments.first()])
//Create a new object just with objectTypeId
ObjectBean aSecondEmployee = im.createObject(9, [Name: "Nisse Hult", Department: departments.first()])
ObjectBean aThirdEmployee = im.createObject(aSecondEmployee.objectTypeId, [Name: "Nisse Hult", Department: departments.first()])
/**
* Gets all values of single object attribute.
* Object Can be ObjectBean/MutableObjectBean,Object Key (string) or object ID (int).
* Attribute can be attribute ID (int) or attribute name (string)
* Returns List of results,
*/
List getObjectAttributeValues(def Object, def Attribute)
This will get the values of a single objects single attribute. If the attribute contains referenced objects, those ObjectBeans will be returned.
/**
* Get multiple attribute values from object
* Object id, ObjectBean, key
* Attributes List of attribute name´s and/or id´s , if left empty all attributes will be returned.
* Returns A map with where the key is the attribute name and the value is an array of values.
*/
Map<String, List> getObjectAttributeValues(def Object, List Attributes = [])
Similar to the previous method, but this allows you to get more than one attribute´s values. If no attributes are given, all will be returned. A map where the Keys are attribute names and values are attribute values will be returned, just like the map that im.updateObjectAttributes() expects as input.
//Because Department is a reference object attribute, ObjectBeans will be returned
List<ObjectBean>departments = im.getObjectAttributeValues(newEmployee, "Department")
List<String>employeeNames = im.getObjectAttributeValues("KEY-456", "Name")
//Get newEmployee´s all attributes
Map newEmployeesAttributes = im.getObjectAttributeValues(newEmployee, [])
Map newEmployeesAttributes = im.getObjectAttributeValues(newEmployee) //This is a shortcut
//Get just some of the attributes
Map newEmployeesContactDetails = im.getObjectAttributeValues(newEmployee, ["Phone", "E-mail", "Home Address"])
/**
* Updates a single objects single attribute with one or multiple values.
* object Can be object ID, Object Key or ObjectBean
* attribute Can be name of Attribute or AttributeID
* value Can be an array of values or a single object
* Returns the new/updated ObjectAttributeBean
*/
ObjectAttributeBean updateObjectAttribute(def object, def attribute, def value)
This method allows you to update a single attribute of a single object, it expects and Object (ObjectBean, Id, Key), an attribute (Name, Id) and a value.
/**
* Updates a single objects multiple attributes with one or multiple values.
* object Can be object ID, Object Key or ObjectBean
* attributeValueMap is a map containing Keys representing AttributeID or Attribute Name and values
* Returns and array of the new/updated ObjectAttributeBean
*/
ArrayList<ObjectAttributeBean> updateObjectAttributes(def object, Map attributeValueMap)
Similar to the previous method but this allows you to update multiple attributes by suppling a Map where the Keys are attributes and the Values are attribute values
//Update an object based on object key
im.updateObjectAttribute("Key-123", Name, "Nisse Hult")
//Update an object based on objectBean, supply a an ApplicationUser object as value
im.updateObjectAttribute(newEmployee, "Jira User", userManager.getUserByName("nisse.hult"))
//Update a select attribute with an array of valid elements
im.updateObjectAttribute(newEmployee, "Responsibilities", ["Purchasing", "Hiring"])
//Update an object based on object id, attribute id and supply a new Date() object as value
im.updateObjectAttribute(12, 49, new Date())
//Set value to an other objectBean using an object key
im.updateObjectAttribute(newEmployee,"Company", "CRM-479")
//Set value to an other objectBean
im.updateObjectAttribute(newEmployee,"Department", departmentObjectBean)
//Here we do all the previous changes in one go by supplying a map with all the attributes and values
im.updateObjectAttributes(newEmployee,
[
Name: "Nisse Hult",
"Jira User" : userManager.getUserByName("nisse.hult"),
Responsibilities, ["Purchasing", "Hiring"],
49 : new Date(),
Company: "CRM-479",
"Department": departmentObjectBean
]
)
/**
* Clears value of attribute
* object, Can be object ID, Object Key or ObjectBean
* attribute, name (string) or id (int)
*/
void clearObjectAttribute(def object, def attribute)
im.clearObjectAttribute("Key-123", "Department")
im.clearObjectAttribute(insightObjectBean, 12)
/**
* Deletes an object
* object Can be object ID, Object Key or ObjectBean
* returns boolean representing success or failure
*/
boolean deleteObject(def object)
/**
* This will create a HTML table showing some or all of an objects attributes
* Object id, ObjectBean, key
* Attributes name or id, if left empty all attributes will be returned.
* Returns a HTML string
*/
String renderObjectToHtml(def Object, List Attributes = [])
Sometimes you might need to display an Insight object in places and ways that Insight and JIRA doesn't support out of the box, this is where IM and ScriptRunner makes a great match. With for example ScriptRunner behaviors you could use IM to display some or all of an objects attributes as a field description in a JSD portal.

To simplify working with Insight Attachments IM represents them with the class SimplifiedAttachmentBean, the job of this class is to make it simpler to bridge the gap between the Insight AttachmentBean and the actual file. It´s important to understand that when the attachment is stored on the server it´s given a new unique name, to access the original name from a SimplifiedAttachmentBean check its originalFileName property.
/**
* It´s likely that you will have to add an import statement when working with SimplifiedAttachmentBean
*/
import customRiadaLibraries.insightmanager.SimplifiedAttachmentBean
/**
* This is a class intended to simplify working with Insight AttachmentBeans
* Once instantiated it will give you easy access to the AttachmentBean it self as well as the related File object
*/
public class SimplifiedAttachmentBean {
public AttachmentBean attachmentBean
public Integer id
public File attachmentFile
public String originalFileName
....
....
}
/**
* This method will retrieve all SimplifiedAttachmentBeans belonging to an object.
* object: key, id or objectbean
* returns: ArrayList containing SimplifiedAttachmentBean
* Note that the File object will have a different file name than the original file name.
*/
ArrayList<SimplifiedAttachmentBean> getAllObjectAttachmentBeans(def object)
/**
* Add an attachment to an object
* object: key, id or objectbean of the object you want to attatch to
* file: the file you´d like to attach
* attachmentName (Optional) Specify a name for the attachment, if non is given the file name will be used
* attachmentComment: (Optional) a comment relevant to the attachment, note that this is not the same as an object comment
* deleteSourceFile: Should the source file be deleted?
* return: A SimplifiedAttachmentBean representing the new attachment
*/
SimplifiedAttachmentBean addObjectAttachment(def object, File file, String attachmentName = "", String attachmentComment = "", boolean deleteSourceFile = false)
/**
* Delete an attachment
* attachment: Id, AttachmentBean or SimplifiedAttachmentBean
* return: true if successful
*/
boolean deleteObjectAttachment(def attachment)
/**
* This method will export the attachments of an Object
* The exported files will be exported to $destinationDirectory/$objectKey/
* The attachment name will be used as filename, if this results in duplicate file names they will be renamed $atachmentName_DUPLICATE1..999
* object: key, id or objectbean of the object you want to export from
* destinationDirectory: The output directory, a new child folder with the $objectKey will be created and the files will be put in to that folder
* return: An Array with the exported File objects
*/
ArrayList<File> exportObjectAttachments(def object, String destinationDirectory)
Example file outpu:
migrateAttachments/
├── TAS-6590
│ ├── Han_Solo.jpg
│ ├── leia.jpg
│ ├── leia.jpg_DUPLICATE1
│ └── leia.jpg_DUPLICATE2
└── TAS-6591
├── leia.jpg
└── palpatine.jpeg
/**
* This method will import object attachments using the following steps:
* 1. Determine source object key based on sourceDirectoryPath sub folder name
* 2. Determine destination object based on matchingIQL
* 3. For every attachment sourceDirectoryPath/$SOURCE_OBJECT_KEY
* 3.1 Determine if the destination object already has the attachment in question and skip it if ignoreDuplicates == true
* 3.2 Attach the file to the destination Object and add the attachment comment attachmentComment if it != ""
* 3.3 If deleteSourceFiles == true, the attached source file will be deleted
*
* sourceDirectoryPath: A folder containing one or more folders with the source objects key as name and the files to be attached in those folders. This is the structure given by exportObjectAttachments()
* matchingIQL: This IQL should match a single destination object in all of Insight. It must contain the keyword SOURCE_OBJECT_KEY which will be replaced at runtime by the source objects key (based on the folder name)
* attachmentComment: (Optional) A comment can be added to the attachment if wanted. SOURCE_OBJECT_KEY may be used in the comment and will be replaced by the source objects key.
* deleteSourceFiles: (Default: False) Should the imported source files be deleted?
* ignoreDuplicates: Should duplicates not be imported? Duplicates are determined based on file name and SHA256 hash.
* return: An Array containing the new SimplifiedAttachmentBeans
*/
ArrayList<SimplifiedAttachmentBean> importObjectAttachments(String sourceDirectoryPath, String matchingIQL = "\"Old Object key\" = SOURCE_OBJECT_KEY", String attachmentComment = "Imported from SOURCE_OBJECT_KEY", boolean deleteSourceFiles = false, boolean ignoreDuplicates = true)
The matchingIQL parameter is of great importance here as it´s used to associate an exported object folder with an object in Insight. It must match exactly one object in all of Insight. It must also contain SOURCE_OBJECT_KEY which will be replaced with the original objects key.
This methods intended use case is that you have exported objects from one insight instance in to another instance and want to also migrate the objects attachments. The new objects (in the destination instance) must have a an attribute containing the original objects key.
It´s recomended to run this in readOnly mode first so that you can check the logs and do a sanity check.
/**
* Get list of all ImportSource for a Schema
* SchemaID Schema ID
* Returns ArrayList with ImportSources
*/
ArrayList<ImportSource> listImports(int SchemaID)
im.listImports() expects a Schemas ID as imput and will in return give you a list of ImportSource-objects. SchemaID can be found by for example looking at the URL when configurting a scheme: http://balerion.local/secure/InsightConfigure.jspa?id=5
/**
* Get the progress object of an import (without triggering it)
* Import can be an int ImportSourceID or ImportSource object.
* Returns a progress object.
*/
Progress getImportProgress(def Import)
im.getImportProgress() expects an ImportSourceId or ImportSource object as returned by listImports(). In return you will get a Progress object that can tell if the import is currently running or when it was last and what was the result of it.
ArrayList<ImportSource>imports = im.listImports(5)
log.info("Listing imports:")
imports.each {importSource ->
log.info("\tName:" + importSource.name)
log.info("\t\tDescription:" + importSource.description)
Progress currentImportProgress = im.getImportProgress(importSource)
if (currentImportProgress.inProgress) {
log.info("\t"*2+ "Currently in progress: " + currentImportProgress.progressInPercent + "%")
}else {
log.info("\t"*2 + "Import was last run:" + currentImportProgress.finishedDate)
}
}
/**
* Starts an Insight Import and by default waits for it to finish
* Import The import to be run, can be an int ImportSourceID or ImportSource object.
* ObjectsToImport What objects to import,if left empty all objects will be imported
* timeOut (millis) defaults to 10min
* Returns Progress object
*/
Progress runImport(def Import, List ObjectsToImport = [], long timeOut = 600000)
im.getImportProgress() expects an ImportSourceId or ImportSource object as returned by listImports(), a list of ObjectTypes (Id, name, bean) to import and a timeout.
If no ObjectTypes are supplied, all will be imported. While the import is running IM will wait until $timeOut is reached, then IM will throw an error. If $timeOut is set to 0, IM will return a progress object immediately which you will have to monitor if you are interested in it´s result and completion.
Progress importProgress = im.runImport(importSource)
Progress importProgress = im.runImport(importSource, ["User", "Group"])
Progress importProgress = im.runImport(imports.last(), [], 0)
while (importProgress.inProgress) {
log.debug("Import Progress ${importProgress.progressInPercent}%")
sleep(100)
}
if (importProgress.resultData.isOK()) {
log.info("\tThe import was successful, duration:" + importDuration)
}
Scripts in JIRA are often triggered by limited users such as JSD Customers but the scripts might still have to escalate its privileges to CRUD Insight objects, because of this IM allows you to set a service user and automatically escalate to that user.
im.setServiceAccount("nisse.hult")
im.autoEscalate = true //Default is true
IM is not heavily commented, rather it has quite extensive logging, to enable all IM logs:
import org.apache.log4j.Level
im.log.setLevel(Level.ALL)
Simply by setting. IM in read only mode you can safely run your script and know that imports wont be triggered, objects wont get created or updated
im.readOnly = true //false is default
/**
* Should events be dispatched when you create/update/delete objects?
* dispatch true or false, default is true
*/
void dispatchEvents(boolean dispatch)
Insight by default fires events when you make changes to objects or create new ones, this is usually a good thing. But if you script is executed by and Insight Automation which is triggered by an update to an object and your script then updates that object, then you have a loop. To avoid this, disable dispatchEvevents()
//After this, this specific instance of InsightManager (im) wont dispatch events.
im.dispatchEvents(false)