1
2
3
4
5
6
7 package org.mule.example.scripting;
8
9
10 import org.mule.api.MuleEventContext;
11 import org.mule.api.lifecycle.Callable;
12 import org.mule.api.transformer.TransformerException;
13 import org.mule.config.i18n.MessageFactory;
14 import org.mule.util.NumberUtils;
15
16
17
18
19 public class AccumulatorComponent implements Callable
20 {
21
22 private String operation = "add";
23
24 private double accumulatedValue = 0;
25
26 public Object onCall(MuleEventContext context) throws Exception
27 {
28 Object msg = context.getMessage().getPayload();
29
30 double data = NumberUtils.toDouble(msg);
31 if (data == NumberUtils.DOUBLE_ERROR)
32 {
33 throw new TransformerException(MessageFactory.createStaticMessage("Unable to convert message to double: " + msg));
34 }
35
36 if (operation.equalsIgnoreCase("add"))
37 {
38 accumulatedValue += data;
39 }
40 else if (operation.equalsIgnoreCase("subtract"))
41 {
42 accumulatedValue -= data;
43 }
44 else if (operation.equalsIgnoreCase("multiply"))
45 {
46 accumulatedValue *= data;
47 }
48 else if (operation.equalsIgnoreCase("divide"))
49 {
50 accumulatedValue /= data;
51 }
52 else
53 {
54 throw new TransformerException(MessageFactory.createStaticMessage("Operation " + operation + " not recognized"));
55 }
56
57
58 return new Double(accumulatedValue);
59 }
60
61 public String getOperation()
62 {
63 return operation;
64 }
65
66 public void setOperation(String operation)
67 {
68 this.operation = operation;
69 }
70 }