1
2
3
4
5
6
7
8
9
10
11 package org.mule.example.scripting;
12
13
14 import org.mule.api.transformer.TransformerException;
15 import org.mule.config.i18n.MessageFactory;
16 import org.mule.transformer.AbstractTransformer;
17 import org.mule.util.NumberUtils;
18
19
20
21
22 public class SimpleMathTransformer extends AbstractTransformer
23 {
24
25 private String operation = "add";
26
27
28 private double factor;
29
30 public SimpleMathTransformer()
31 {
32 registerSourceType(Number.class);
33 setReturnClass(Number.class);
34 }
35
36 public Object doTransform(Object src, String encoding) throws TransformerException
37 {
38 double data = NumberUtils.toDouble(src);
39 if (data == NumberUtils.DOUBLE_ERROR)
40 {
41 throw new TransformerException(MessageFactory.createStaticMessage("Unable to convert message to double: " + src));
42 }
43
44 double result;
45 if (operation.equalsIgnoreCase("add"))
46 {
47 result = data + factor;
48 }
49 else if (operation.equalsIgnoreCase("subtract"))
50 {
51 result = data - factor;
52 }
53 else if (operation.equalsIgnoreCase("multiply"))
54 {
55 result = data * factor;
56 }
57 else if (operation.equalsIgnoreCase("divide"))
58 {
59 result = data / factor;
60 }
61 else
62 {
63 throw new TransformerException(MessageFactory.createStaticMessage("Operation " + operation + " not recognized"));
64 }
65
66
67 return new Double(result);
68 }
69
70 public String getOperation()
71 {
72 return operation;
73 }
74
75 public void setOperation(String operation)
76 {
77 this.operation = operation;
78 }
79
80 public double getFactor()
81 {
82 return factor;
83 }
84
85 public void setFactor(double factor)
86 {
87 this.factor = factor;
88 }
89 }