}
@Override
public void process(final Reader reader, final Writer writer)
throws IOException {
final StopWatch watch = new StopWatch();
watch.start("rhino setup");
RhinoExecutor.execute(new JsTask<String>() {
@Override
public String run(final Global global, final Context context,
final Scriptable scope) throws IOException {
watch.stop();
watch.start("r.js");
ServletContext servletContext = servletContext();
final String tmpdir = System.getProperty("java.io.tmpdir");
final HttpServletRequest currentRequest = currentRequest();
final String profile = currentRequest.getParameter("profile");
final String uri = currentRequest.getRequestURI().replace(
servletContext.getContextPath(), "");
final String baseName = getBaseName(uri);
final String name = baseName + "-" + System.nanoTime();
final String appDir = servletContext.getRealPath("/");
final String base = appDir;
// mkdirs
new File(base).mkdirs();
final String baseBuild = base + "/build";
final File tmpIn = new File(base, name + ".js");
final File out = new File(tmpdir, name + "-bundle.js");
// safe the current input to file and use it. doing this we make sure
// that if any previous processor in the chain changed the input we use
// that in r.js.
WroHelper.safeCopy(reader, new FileWriter(tmpIn));
// r.js arguments
List<String> args = Lists.newArrayList(
"-o",
"name=" + name,
"baseUrl=" + base,
"out=" + out.getAbsolutePath(),
"optimize=none"
);
// Find a specific build profile for the given file.
File build =
buildFile(baseBuild, baseName, profile, mode.name());
if (build == null) {
// no luck, find a global profile per environment
build = buildFile(baseBuild, "build", profile, mode.name());
if (build == null) {
// no luck, defaults to build.js
build = new File(baseBuild, "build.js");
}
}
if (build.exists()) {
logger.debug("Build's profile found: {}", build.getName());
args.add(1, build.getAbsolutePath());
}
global.defineProperty("arguments",
context.newArray(global, args.toArray(new Object[args.size()])),
ScriptableObject.DONTENUM);
logger.debug("r.js {}", StringUtils.join(args, " "));
// execute r.js
Reader bundle = null;
try {
context.evaluateString(scope, source, "r.js", 1, null);
// Read the r.js output.
bundle = new FileReader(out);
String content = IOUtils.toString(bundle).replace(name, baseName);
WroHelper.safeCopy(new StringReader(content), writer);
return null;
} finally {
logger.debug("Deleting: {}", tmpIn);
FileUtils.deleteQuietly(tmpIn);
logger.debug("Deleting: {}", out);
FileUtils.deleteQuietly(out);
watch.stop();
logger.debug(watch.prettyPrint());
}
}
});
}