1 16 package org.apache.cocoon.components.flow.apples.samples; 17 18 import java.math.BigDecimal ; 19 import java.util.HashMap ; 20 import java.util.Map ; 21 22 import org.apache.avalon.framework.logger.AbstractLogEnabled; 23 import org.apache.cocoon.ProcessingException; 24 import org.apache.cocoon.components.flow.apples.AppleController; 25 import org.apache.cocoon.components.flow.apples.AppleRequest; 26 import org.apache.cocoon.components.flow.apples.AppleResponse; 27 28 39 public class CalculationApple extends AbstractLogEnabled implements AppleController { 40 41 BigDecimal inputA; 42 BigDecimal inputB; 43 String inputOp; 44 BigDecimal output; 45 46 47 public String toString() { 48 return "CalculationApple[ a=" + this.inputA + " | b=" + this.inputB 49 + " | op = " + this.inputOp + " | result = " + this.output + "]"; 50 } 51 52 public void process(AppleRequest req, AppleResponse res) throws ProcessingException { 53 String changeTo = processRequest(req); 54 getLogger().debug(toString()); 55 showNextState(res, changeTo); 56 } 57 58 private String processRequest(AppleRequest req) { 59 String changeRequest = req.getCocoonRequest().getParameter("change"); 60 61 String newA = req.getCocoonRequest().getParameter("a"); 62 if (newA != null) { 63 this.inputA = new BigDecimal (newA); 64 } 66 String newB = req.getCocoonRequest().getParameter("b"); 67 if (newB != null) { 68 this.inputB = new BigDecimal (newB); 69 } 71 String newOp = req.getCocoonRequest().getParameter("operator"); 72 if (newOp != null) { 73 this.inputOp = newOp; 74 } 75 calculate(); 77 78 return changeRequest; 79 } 80 81 82 private void calculate() { 83 if (this.inputA == null || this.inputB == null) { 84 this.output = null; 85 } else if("plus".equals(this.inputOp)) { 86 this.output = this.inputA.add(this.inputB); 87 } else if("minus".equals(this.inputOp)) { 88 this.output = this.inputA.add(this.inputB.negate()); 89 } else if("multiply".equals(this.inputOp)) { 90 this.output = this.inputA.multiply(this.inputB); 91 } else if("divide".equals(this.inputOp)) { 92 this.output = this.inputA.divide(this.inputB, BigDecimal.ROUND_HALF_EVEN); 93 } else { this.output = null; 95 } 96 } 97 98 private void showNextState(AppleResponse res, String changeTo) { 99 Object bizdata = buildBizData(); 100 101 if (changeTo != null) { 102 res.sendPage("calc/get" + changeTo, bizdata); 103 } else if (this.inputA == null) { 104 res.sendPage("calc/getNumberA", null); 105 } else if (this.inputB == null) { 106 res.sendPage("calc/getNumberB", bizdata); 107 } else if (this.inputOp == null) { 108 res.sendPage("calc/getOperator", bizdata); 109 } else { 110 res.sendPage("calc/displayResult", bizdata); 111 } 112 } 113 114 private Object buildBizData() { 115 Map bizdata = new HashMap (); 116 bizdata.put("a", this.inputA); 117 bizdata.put("b", this.inputB); 118 bizdata.put("operator", this.inputOp); 119 bizdata.put("result", this.output); 120 return bizdata; 121 } 122 123 } 124 | Popular Tags |