1 17 package org.apache.servicemix.beanflow.support; 18 19 import org.apache.servicemix.beanflow.Workflow; 20 import org.apache.servicemix.beanflow.WorkflowStep; 21 22 import java.lang.reflect.Method ; 23 24 35 public class ReflectionInterpreter<T> implements Interpreter<T> { 36 37 protected static final Class [] NO_TYPE_ARGUMENTS = {}; 38 protected static final Object [] NO_PARAMETER_ARGUMENTS = {}; 39 40 @SuppressWarnings ("unchecked") 41 public void executeStep(T step, Workflow<T> workflow) { 42 if (step instanceof WorkflowStep) { 43 WorkflowStep<T> workflowStep = (WorkflowStep<T>) step; 44 T nextStep = workflowStep.execute(workflow); 45 if (nextStep != null) { 46 workflow.addStep(nextStep); 47 } 48 else { 49 workflow.suspend(); 50 } 51 } 52 else if (step instanceof Runnable ) { 53 Runnable runnable = (Runnable ) step; 54 runnable.run(); 55 goToNextSequence(step, workflow); 56 } 57 else if (step != null) { 58 String name = step.toString(); 59 executeNamedStep(name, workflow); 60 } 61 } 62 63 71 protected void goToNextSequence(T nextStep, Workflow<T> workflow) { 72 if (nextStep instanceof Enum ) { 73 Enum step = (Enum ) nextStep; 74 try { 75 Object [] enumValues = EnumHelper.getEnumValues(step.getClass()); 76 int index = step.ordinal(); 77 if (++index < enumValues.length) { 78 workflow.addStep((T) enumValues[index]); 79 } 80 else { 81 workflow.stop(); 82 } 83 } 84 catch (Exception e) { 85 workflow.fail("Could not extract the values of the enum: " + nextStep + " due to: " + e, e); 86 } 87 } 88 else { 89 workflow.suspend(); 90 } 91 } 92 93 public void executeNamedStep(String step, Workflow<T> workflow) { 94 Class <? extends Workflow> type = workflow.getClass(); 95 try { 96 Method method = type.getMethod(step, NO_TYPE_ARGUMENTS); 97 Object answer = method.invoke(workflow, NO_PARAMETER_ARGUMENTS); 98 handleStepResult(step, workflow, answer); 99 } 100 catch (Exception e) { 101 workflow.onStepException(step, e); 102 } 103 } 104 105 public void validateStepsExist(Object [] stepValues, Workflow<T> workflow) { 106 Class <? extends Workflow> type = workflow.getClass(); 107 for (int i = 0; i < stepValues.length; i++) { 108 Object value = stepValues[i]; 109 if (!isValidStep(value)) { 110 String step = value.toString(); 111 try { 112 type.getMethod(step, NO_TYPE_ARGUMENTS); 113 } 114 catch (Exception e) { 115 workflow.fail("No " + step + "() method is available in class: " + type.getName() 116 + " so unable to bind the code to the enumeration of steps", e); 117 } 118 } 119 } 120 } 121 122 126 protected boolean isValidStep(Object value) { 127 return value instanceof WorkflowStep || value instanceof Runnable ; 128 } 129 130 @SuppressWarnings ("unchecked") 131 protected void handleStepResult(String step, Workflow workflow, Object result) { 132 if (result != null) { 133 workflow.addStep(result); 134 } 135 else { 136 workflow.suspend(); 137 } 138 } 139 } 140 | Popular Tags |