01: /*
02: * Licensed to the Apache Software Foundation (ASF) under one or more
03: * contributor license agreements. See the NOTICE file distributed with
04: * this work for additional information regarding copyright ownership.
05: * The ASF licenses this file to You under the Apache License, Version 2.0
06: * (the "License"); you may not use this file except in compliance with
07: * the License. You may obtain a copy of the License at
08: *
09: * http://www.apache.org/licenses/LICENSE-2.0
10: *
11: * Unless required by applicable law or agreed to in writing, software
12: * distributed under the License is distributed on an "AS IS" BASIS,
13: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14: * See the License for the specific language governing permissions and
15: * limitations under the License.
16: */
17: package org.apache.cocoon.samples.flow.java;
18:
19: import org.apache.cocoon.components.flow.java.AbstractContinuable;
20: import org.apache.cocoon.components.flow.java.VarMap;
21:
22: public class CalculatorFlow extends AbstractContinuable {
23:
24: private int count = 1;
25:
26: public void doCalculator() {
27: float a = getNumber("a", 0f, 0f);
28: float b = getNumber("b", a, 0f);
29: String op = getOperator(a, b);
30:
31: if (op.equals("plus")) {
32: sendResult(a, b, op, a + b);
33: } else if (op.equals("minus")) {
34: sendResult(a, b, op, a - b);
35: } else if (op.equals("multiply")) {
36: sendResult(a, b, op, a * b);
37: } else if (op.equals("divide")) {
38: if (b == 0f)
39: sendMessage("Error: Cannot divide by zero!");
40: sendResult(a, b, op, a / b);
41: } else {
42: sendMessage("Error: Unkown operator!");
43: }
44:
45: count++;
46: }
47:
48: private float getNumber(String name, float a, float b) {
49: String uri = "page/calculator-" + name.toLowerCase();
50: sendPageAndWait(uri, new VarMap().add("a", a).add("b", b).add(
51: "count", count));
52:
53: float value = 0f;
54: try {
55: value = Float.parseFloat(getRequest().getParameter(name));
56: } catch (Exception e) {
57: sendMessage("Error: \"" + getRequest().getParameter(name)
58: + "\" is not a correct number!");
59: }
60: return value;
61: }
62:
63: private String getOperator(float a, float b) {
64: sendPageAndWait("page/calculator-operator", new VarMap().add(
65: "a", a).add("b", b).add("count", count));
66: return getRequest().getParameter("operator");
67: }
68:
69: private void sendResult(float a, float b, String op, float result) {
70: sendPage("page/calculator-result", new VarMap().add("a", a)
71: .add("b", b).add("operator", op).add("result", result)
72: .add("count", count));
73: }
74:
75: private void sendMessage(String message) {
76: sendPageAndWait("page/calculator-message", new VarMap().add(
77: "message", message).add("count", count));
78: }
79: }
|