import com.day.text.Text; //导入依赖的package包/类
/**
* This is where all the work is done in processing the ClientLibrary.
*
* @param type the client library type (CSS or JS)
* @param source The client library to process; you can get the location, the final contents and options.
* @param output The writer that can expose updates to the client library.
* @param options The cq:clientLibraryFolder process options.
* @return true if the output should be used, false if the source should be used as the output.
* @throws IOException
*/
@Override
public boolean process(@Nonnull LibraryType type, @Nonnull ScriptResource source, @Nonnull Writer output, @Nonnull Map options) throws IOException {
if (!handles(type)) {
// We must perform the handles check ourselves n process at least up to AEM 6.3 GA
return false;
}
log.debug("Source Name: {}", source.getName()); // -> /apps/my-site/clientlibs/clientlib-foo.css
log.debug("Source Size: {}", source.getSize()); // -> 654932 (size in bytes)
log.debug("Source Reader: {}", IOUtils.toString(source.getReader())); // -> Text contents of outputed file
// 1. Read from source.reader()
// 2. Transform contents from #1
// 3. Write final data to output
String externalizerDomain = StringUtils.defaultIfEmpty(options.get("externalizerDomain"), "publish");
// Put some better error handling if externalizerDomain is not provided
// Read in the CSS to parse and update
final String input = IOUtils.toString(source.getReader());
// Set up a StringBuffer to record the the transformed content
final StringBuffer transformedOutput = new StringBuffer(input.length());
// Create a matcher so we can find things that look like URLs
final Matcher m = URL_PATTERN.matcher(input);
// Track if we actually make changes or not
boolean dirty = false;
// Search the CSS for the URL PATTERN so we can update them
while (m.find()) {
// Use the match groups to get the part of the match we want to transform
final String url = m.group(2);
// Check to make sure we don't rewrite external links
if (!StringUtils.startsWithAny(url, new String[]{"//", "http://", "https://" } )) {
log.debug("Found local url in CSS [ {} ]", url);
// Convert the relative path to absolute
String externalUrl = Text.makeCanonicalPath(source.getName() + url);
// Prefix the URL w the external domain
externalUrl = externalizerDomain + externalUrl;
// Replace the match w the updated doamin
m.appendReplacement(transformedOutput, Matcher.quoteReplacement(externalUrl));
// Mark as dirty
dirty = true;
}
}
if (dirty) {
// If we made changes then write it to the output
m.appendTail(transformedOutput);
output.write(transformedOutput.toString());
output.flush();
}
// Return true only if we made changes, false if we want to use what was input to us.
return dirty;
}