1 16 package scriptella.driver.jexl; 17 18 import org.apache.commons.jexl.JexlContext; 19 import org.apache.commons.jexl.Script; 20 import org.apache.commons.jexl.ScriptFactory; 21 import scriptella.spi.AbstractConnection; 22 import scriptella.spi.ConnectionParameters; 23 import scriptella.spi.ParametersCallback; 24 import scriptella.spi.ProviderException; 25 import scriptella.spi.QueryCallback; 26 import scriptella.spi.Resource; 27 import scriptella.util.IOUtils; 28 29 import java.io.IOException ; 30 import java.util.IdentityHashMap ; 31 import java.util.Map ; 32 33 40 public class JexlConnection extends AbstractConnection { 41 private Map <Resource, Script> cache = new IdentityHashMap <Resource, Script>(); 42 43 48 public JexlConnection(ConnectionParameters parameters) { 49 super(Driver.DIALECT, parameters); 50 } 51 52 public void executeScript(Resource scriptContent, ParametersCallback parametersCallback) throws ProviderException { 53 Script script = compile(scriptContent); 54 try { 55 JexlContext ctx = new JexlContextMap(parametersCallback); 56 script.execute(ctx); 57 } catch (Exception e) { 58 throw new JexlProviderException("Failed to execute JEXL script", e); 59 } 60 } 61 62 public void executeQuery(Resource queryContent, ParametersCallback parametersCallback, QueryCallback queryCallback) throws ProviderException { 63 Script query = compile(queryContent); 64 try { 65 JexlContextMap ctx = new JexlContextMap(parametersCallback); 66 ctx.put("query", new Query(queryCallback, ctx)); 67 query.execute(ctx); 68 } catch (Exception e) { 69 throw new JexlProviderException("Failed to execute JEXL script", e); 70 } 71 } 72 73 private Script compile(Resource resource) { 74 Script script = cache.get(resource); 75 if (script == null) { 76 String s; 77 try { 78 s = IOUtils.toString(resource.open()); 79 } catch (IOException e) { 80 throw new JexlProviderException("Unable to open resource", e); 81 } 82 83 try { 84 cache.put(resource, script = ScriptFactory.createScript(s)); 85 } catch (Exception e) { 86 throw new JexlProviderException("Failed to compile JEXL script", e); 87 } 88 } 89 return script; 90 } 91 92 93 96 public void close() throws ProviderException { 97 } 98 99 } 100 | Popular Tags |