* @throws IOException resolving the resources failed
*/
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<String, String>();
// maps "name" --> dataSource
final Map<String, DataSource> dataSourceCache = new HashMap<String, DataSource>();
// 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, dataSource.getName());
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