1 package com.github.searls.jasmine.coffee; 2 3 import com.gargoylesoftware.htmlunit.MockWebConnection; 4 import com.gargoylesoftware.htmlunit.ScriptResult; 5 import com.gargoylesoftware.htmlunit.WebClient; 6 import com.gargoylesoftware.htmlunit.html.HtmlPage; 7 import com.github.searls.jasmine.io.IOUtilsWrapper; 8 import org.apache.commons.lang3.StringEscapeUtils; 9 10 import java.io.IOException; 11 import java.util.Collections; 12 import java.util.Map; 13 import java.util.WeakHashMap; 14 15 public class CoffeeScript { 16 17 private static Map<String, String> cache = Collections.synchronizedMap(new WeakHashMap<String, String>()); 18 19 private final ThreadLocal<HtmlPage> htmlPage = new ThreadLocal<HtmlPage>() { 20 @Override 21 protected HtmlPage initialValue() { 22 MockWebConnection webConnection = new MockWebConnection(); 23 WebClient webClient = new WebClient(); 24 webClient.setWebConnection(webConnection); 25 try { 26 HtmlPage page = webClient.getPage(WebClient.URL_ABOUT_BLANK); 27 page.executeJavaScript(ioUtilsWrapper.toString("/vendor/js/coffee-script.js")); 28 return page; 29 } catch (IOException e) { 30 throw new RuntimeException(e); 31 } 32 } 33 }; 34 35 private final IOUtilsWrapper ioUtilsWrapper = new IOUtilsWrapper(); 36 37 public String compile(String coffee) throws IOException { 38 String escapedCoffee = StringEscapeUtils.escapeEcmaScript(coffee); 39 return cache.containsKey(escapedCoffee) ? cache.get(escapedCoffee) : compileAndCache(escapedCoffee); 40 } 41 42 private String compileAndCache(String input) { 43 ScriptResult scriptResult = htmlPage.get().executeJavaScript(String.format("CoffeeScript.compile(\"%s\");", input)); 44 String result = (String) scriptResult.getJavaScriptResult(); 45 cache.put(input, result); 46 return result; 47 } 48 49 }