How to Dynamically Retrieve Source IDs with ISCRuleUtil

I recently created a uniqueness check following SailPoint’s documentation:
Rule Utility Documentation,
and was surprised to see that you had to hardcode the environment-specific source ID.

While searching for a better approach, I found this helpful discussion:
Trying to Use idn.getSourceAttributeBySourceName to Get a Source ID,
but I thought I could expand on it and share my solution for anyone else looking to have a single rule that works across all environments.

Solution Overview

boolean isUnique(String username) throws Exception {

	String[] sourceNames = {
		"Active Directory [source]",
		"Active Directory - Privileged [source]",
		"SuccessFactors [source]",
		"SAP ERP [source]",
	};

	List SOURCE_IDS = new ArrayList();

	for (String sourceName : sourceNames) {
		String sourceId = idn.getSourceAttributeBySourceName(sourceName, "myCompanyNameSourceId");
		if (sourceId != null && !sourceId.isEmpty()) {
			SOURCE_IDS.add(sourceId);
		}
	}
	
	String PROMOTED_ATTR_NAME = "systemUsernameSearch";
    String SEARCH_OP = "Equals";
    List SEARCH_VALUES = new ArrayList();
    SEARCH_VALUES.add(username);

    int count = idn.attrSearchCountAccounts(SOURCE_IDS, PROMOTED_ATTR_NAME, SEARCH_OP, SEARCH_VALUES);

    return count == 0;
}

Additional Note

The source ID is not natively available via any built-in Java methods (as far as I can tell), I added a custom JSON property to the connectorAttributes object of all sources, where I manually copied the source IDs. This allows the rule to dynamically retrieve them without hardcoding.

Hope this helps others