Skip to content

Instantly share code, notes, and snippets.

@russelldb
Created May 29, 2009 08:17
Show Gist options
  • Save russelldb/119849 to your computer and use it in GitHub Desktop.
Save russelldb/119849 to your computer and use it in GitHub Desktop.
package uk.co.****.****.presentation.web.util.jawr;
import net.jawr.web.resource.bundle.postprocess.ResourceBundlePostProcessor;
import net.jawr.web.resource.bundle.postprocess.BundleProcessingStatus;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import javax.servlet.ServletContext;
/**
* A Q n D Bundle Post Processor that moves any @imports that have been marooned in the middle of the
* bundle file to the top. Assumes that csspathrewriter file post processor is run
* <p/>
*
*/
public class CSSImportPostProcessor implements ResourceBundlePostProcessor {
private static final Pattern AT_IMPORT_RE = Pattern.compile("(@import url.*;)");
private static final Pattern URL_PATTERN = Pattern.compile( "url\\(\\s*\"([^\\)]*)\"\\s*\\)" );
/**
* Postprocess a bundle of resources.
*
* @param status the BundleProcessingStatus
* @param bundleString StringBuffer Joined resources.
* @return StringBuffer a buffer containing the postprocessed bundle.
*/
public StringBuffer postProcessBundle( final BundleProcessingStatus status, final StringBuffer bundleString ) {
StringBuffer result = new StringBuffer( );
//this is a hack, use the ServletContext context path and jawr css base property
String cssImportBase = (String)status.getJawrConfig().getConfigProperties().get( "jawr.css.importurl.base" );
Matcher matcher = AT_IMPORT_RE.matcher( bundleString );
while(matcher.find()) {
String importStatement = matcher.group();
importStatement = fixURL(importStatement, cssImportBase);
//we need to resolve the path, JAWR will have made paths to imports assuming that ALL css is handled by the servlet
result.append(importStatement).append("\n");
}
result.append("\n").append(matcher.replaceAll( "" ));
//quick and dirty chaining to get around bug in JAWR with 2 custom post processors
return new CSSImagePostProcessor().postProcessBundle( status, result);
}
private String fixURL(String importStatement, String cssImportBase) {
StringBuilder url = new StringBuilder();
Matcher m = URL_PATTERN.matcher( importStatement );
url.append(m.replaceAll( "url(\""+ cssImportBase + "$1\")" ));
return url.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment