1 9 10 package org.nanocontainer.script.jruby; 11 12 import java.io.IOException ; 13 import java.io.Reader ; 14 import java.io.StringWriter ; 15 import java.util.Collections ; 16 17 import org.jruby.IRuby; 18 import org.jruby.exceptions.RaiseException; 19 import org.jruby.javasupport.JavaEmbedUtils; 20 import org.jruby.runtime.builtin.IRubyObject; 21 import org.nanocontainer.integrationkit.PicoCompositionException; 22 import org.nanocontainer.reflection.DefaultNanoPicoContainer; 23 import org.nanocontainer.script.NanoContainerMarkupException; 24 import org.nanocontainer.script.ScriptedContainerBuilder; 25 import org.picocontainer.PicoContainer; 26 import org.picocontainer.alternatives.EmptyPicoContainer; 27 28 35 public class JRubyContainerBuilder extends ScriptedContainerBuilder { 36 public static final String MARKUP_EXCEPTION_PREFIX = "nanobuilder: "; 37 38 private String script; 39 40 public JRubyContainerBuilder(Reader script, ClassLoader classLoader) { 41 super(script, classLoader); 42 this.script = toString( script ); 43 } 44 45 private String toString(Reader script) { 46 int charsRead; 47 char[] chars = new char[1024]; 48 StringWriter writer = new StringWriter (); 49 try { 50 while ((charsRead = script.read(chars)) != -1) { 51 writer.write(chars, 0, charsRead); 52 } 53 } catch (IOException e) { 54 throw new RuntimeException ("unable to read script from reader", e); 55 } 56 return writer.toString(); 57 } 58 59 protected PicoContainer createContainerFromScript(PicoContainer parentContainer, Object assemblyScope) { 60 if (parentContainer == null) { 61 parentContainer = new EmptyPicoContainer(); 62 } 63 parentContainer = new DefaultNanoPicoContainer(getClassLoader(), parentContainer); 64 65 IRuby ruby = JavaEmbedUtils.initialize(Collections.EMPTY_LIST); 66 ruby.getLoadService().require("org/nanocontainer/script/jruby/nanobuilder"); 67 ruby.defineReadonlyVariable("$parent", JavaEmbedUtils.javaToRuby(ruby, parentContainer)); 68 ruby.defineReadonlyVariable("$assembly_scope", JavaEmbedUtils.javaToRuby(ruby, assemblyScope)); 69 try { 70 IRubyObject result = ruby.evalScript(script); 71 return (PicoContainer) JavaEmbedUtils.rubyToJava(ruby, result, PicoContainer.class); 72 } catch (RaiseException re) { 73 if (re.getCause() instanceof NanoContainerMarkupException) { 74 throw (NanoContainerMarkupException) re.getCause(); 75 } 76 String message = (String ) JavaEmbedUtils.rubyToJava(ruby, re.getException().message, String .class); 77 if (message.startsWith(MARKUP_EXCEPTION_PREFIX)) { 78 throw new NanoContainerMarkupException(message.substring(MARKUP_EXCEPTION_PREFIX.length())); 79 } else { 80 throw new PicoCompositionException(message, re); 81 } 82 } 83 } 84 } 85 | Popular Tags |