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