in commons-email2-jakarta/src/main/java/org/apache/commons/mail2/jakarta/ImageHtmlEmail.java [113:171]
private String replacePattern(final String htmlMessage, final Pattern pattern) throws EmailException, IOException {
DataSource dataSource;
final StringBuffer stringBuffer = new StringBuffer();
// maps "cid" --> name
final Map<String, String> cidCache = new HashMap<>();
// maps "name" --> dataSource
final Map<String, DataSource> dataSourceCache = new HashMap<>();
// in the String, replace all "img src" with a CID and embed the related
// image file if we find it.
final Matcher matcher = pattern.matcher(htmlMessage);
// the matcher returns all instances one by one
while (matcher.find()) {
// in the RegEx we have the <src> element as second "group"
final String resourceLocation = matcher.group(2);
// avoid loading the same data source more than once
if (dataSourceCache.get(resourceLocation) == null) {
// in lenient mode we might get a 'null' data source if the resource was not found
dataSource = getDataSourceResolver().resolve(resourceLocation);
if (dataSource != null) {
dataSourceCache.put(resourceLocation, dataSource);
}
} else {
dataSource = dataSourceCache.get(resourceLocation);
}
if (dataSource != null) {
String name = dataSource.getName();
if (EmailUtils.isEmpty(name)) {
name = resourceLocation;
}
String cid = cidCache.get(name);
if (cid == null) {
cid = embed(dataSource, name);
cidCache.put(name, cid);
}
// if we embedded something, then we need to replace the URL with
// the CID, otherwise the Matcher takes care of adding the
// non-replaced text afterwards, so no else is necessary here!
matcher.appendReplacement(stringBuffer, Matcher.quoteReplacement(matcher.group(1) + "cid:" + cid + matcher.group(3)));
}
}
// append the remaining items...
matcher.appendTail(stringBuffer);
cidCache.clear();
dataSourceCache.clear();
return stringBuffer.toString();
}