1 package org.sapia.soto.config; 2 3 import org.dom4j.io.SAXReader; 4 5 import org.sapia.util.text.TemplateContextIF; 6 import org.sapia.util.xml.ProcessingException; 7 import org.sapia.util.xml.confix.ConfigurationException; 8 import org.sapia.util.xml.confix.XMLConsumer; 9 import org.sapia.util.xml.confix.Dom4jProcessor; 10 import org.sapia.util.xml.confix.ObjectCreationCallback; 11 import org.sapia.util.xml.confix.ObjectFactoryIF; 12 import org.xml.sax.InputSource ; 13 14 import java.util.ArrayList ; 15 import java.util.List ; 16 17 18 27 public class Choose implements ObjectCreationCallback { 28 private List _whens = new ArrayList (); 29 private Otherwise _otherwise; 30 private TemplateContextIF _ctx; 31 private ObjectFactoryIF _fac; 32 33 public Choose(TemplateContextIF ctx, ObjectFactoryIF fac) { 34 _ctx = ctx; 35 _fac = fac; 36 } 37 38 public When createWhen() { 39 When whenObj = new When(_ctx, _fac); 40 _whens.add(whenObj); 41 42 return whenObj; 43 } 44 45 public Otherwise createOtherwise() { 46 if (_otherwise != null) { 47 throw new IllegalArgumentException ( 48 "'otherwise' element already specified"); 49 } 50 51 return _otherwise = new Otherwise(_ctx, _fac); 52 } 53 54 public Object onCreate() throws ConfigurationException { 55 When current; 56 57 for (int i = 0; i < _whens.size(); i++) { 58 current = (When) _whens.get(i); 59 60 if (current.isEqual()) { 61 return current.create(); 62 } 63 } 64 65 if (_otherwise != null) { 66 return _otherwise.create(); 67 } 68 69 return new NullObjectImpl(); 70 } 71 72 public static class When extends Condition { 73 When(TemplateContextIF ctx, ObjectFactoryIF fac) { 74 super("when", ctx, fac); 75 } 76 } 77 78 public static final class Otherwise implements XMLConsumer{ 79 private TemplateContextIF _ctx; 80 private ObjectFactoryIF _fac; 81 private org.dom4j.Element _elem; 82 83 Otherwise(TemplateContextIF ctx, ObjectFactoryIF fac) { 84 _ctx = ctx; 85 _fac = fac; 86 } 87 88 public Object create() throws ConfigurationException { 89 if (_elem == null) { 90 return new NullObjectImpl(); 91 } 92 93 Dom4jProcessor proc = new Dom4jProcessor(_fac); 94 95 try { 96 return proc.process(null, _elem); 97 } catch (ProcessingException e) { 98 throw new ConfigurationException("Could not process xml nested in 'if' element", 99 e); 100 } 101 } 102 103 106 public void consume(InputSource is) throws Exception { 107 if (_elem != null) { 108 throw new ConfigurationException("'choose' only takes a SINGLE nested xml element"); 109 } 110 SAXReader reader = new SAXReader(); 111 _elem = reader.read(is).getRootElement(); 112 } 113 } 114 } 115 116 | Popular Tags |