Searching by custom field value in JIRA 3.2

Here is a code sample for JIRA 3.2 that finds issues with a given custom field value:

Issue result = null;
SearchRequest sr = new SearchRequest(true); // search without security checks

CustomFieldParamsImpl cfpi = new CustomFieldParamsImpl(cfTicketID);
cfpi.addValue(Collections.singleton("" + ticketId));
        
ExactTextSearcher ts = new ExactTextSearcher(new StringConverter());
List parameters = ts.makeSearchParameters(cfTicketID, cfpi);
        
Iterator it = parameters.iterator();
while (it.hasNext()) {
    SearchParameter searchParameter = (SearchParameter) it.next();
    sr.addParameter(searchParameter);
}

try {
    List issues = issueManager.execute(sr, adminUser);
            
    it = issues.iterator();
    while (it.hasNext()) {
        Issue issue = issueUtilsBean.getIssueObject((GenericValue) it.next());
        // another equals is necessary as the ExtactTextSearch is not that exact :-(
        if (issue.getCustomFieldValue(cfTicketID).equals("" + ticketId)) {
            if (result == null) {
                result = issue;
            } else {
                log.warn("there are several issues (" + issues.size() + ") with the same Ticket ID (" + ticketId + ")");
            }
        }
    }
}
catch (SearchException e) {
    log.info("error during search " + e.toString());
    result = null;
}
        
return result;

Please note that in the above sample cfTicketID is an instance of a Custom Field that can be retrieved with:

CustomField cfTicketID = customFieldManager.getCustomFieldObject(id);

and ticketId is the text value to search for.

Big thanks to Marcel Müller for making this code available!

Labels

 
(None)