1 package org.jicengine.element.impl; 2 3 import org.jicengine.element.*; 4 import org.jicengine.operation.*; 5 import java.util.*; 6 17 public class SwitchCompiler extends ElementCompiler { 18 19 public SwitchCompiler(String name, Location location, String [] parameters) throws ElementException 20 { 21 super(name, location); 22 23 getElement().setConstructor(new Chooser(parameters[0])); 24 } 25 26 32 protected ActionElement handleLooseVariableElement(final VariableElement child) throws ElementException 33 { 34 37 ((Chooser)getElement().getConstructor()).addCase(child); 39 40 return new ActionElement(){ 42 public void execute(Context context, Object parentInstance) 43 { 44 } 45 public String getName() 46 { 47 return child.getName(); 48 } 49 public Location getLocation() 50 { 51 return child.getLocation(); 52 } 53 public boolean isExecuted(Context outerContext, Object parentInstance) 54 { 55 return false; 56 } 57 }; 58 } 59 60 public class Chooser implements Operation { 61 private String variable; 62 private List caseNames = new ArrayList(); 63 private List cases = new ArrayList(); 64 private VariableElement defaultCase; 65 66 public Chooser(String variable) 67 { 68 this.variable = variable; 69 } 70 71 public void addCase(VariableElement child) 72 { 73 if( child.getName().equals("default") ){ 74 this.defaultCase = child; 75 } 76 else { 77 this.cases.add(child); 78 this.caseNames.add(child.getName()); 79 } 80 } 81 82 public boolean needsParameters() 83 { 84 return true; 85 } 86 87 public boolean needsParameter(String name) 88 { 89 return name.equals(this.variable); 90 } 91 92 public Object execute(Context context) throws OperationException 93 { 94 Object variableValue = new VariableValueOperation(this.variable).execute(context); 95 96 String stringValue = String.valueOf(variableValue); 97 98 VariableElement selected = null; 99 for (int i = 0; i < this.caseNames.size(); i++) { 100 String candidate = this.caseNames.get(i).toString(); 101 if( candidate.equals(stringValue) ){ 102 selected = (VariableElement) this.cases.get(i); 104 break; 105 } 106 } 107 108 if( selected == null ){ 109 if( this.defaultCase != null ){ 110 selected = this.defaultCase; 111 } 112 else { 113 throw new OperationException("Case '" + stringValue + "' not found among " + this.caseNames); 114 } 115 } 116 Context elementContext = ((LocalContext)context).getParent(); 117 try { 118 Object result = selected.getValue(elementContext, null); 119 return result; 120 } catch (ElementException e){ 121 throw new OperationException(e.getMessage(), e); 122 } 123 } 124 } 125 126 } 127 | Popular Tags |