View Javadoc
1   /*
2    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
3    * The software in this package is published under the terms of the CPAL v1.0
4    * license, a copy of which has been included with this distribution in the
5    * LICENSE.txt file.
6    */
7   package org.mule.example.scripting;
8   
9   
10  import org.mule.api.transformer.DataType;
11  import org.mule.api.transformer.TransformerException;
12  import org.mule.config.i18n.MessageFactory;
13  import org.mule.transformer.AbstractTransformer;
14  import org.mule.transformer.types.DataTypeFactory;
15  import org.mule.util.NumberUtils;
16  
17  /**
18   * A simple transformer which adds/subtracts/multiplies/divides a constant factor to numeric messages.
19   */
20  public class SimpleMathTransformer extends AbstractTransformer
21  {
22      /** Operation to perform: "add", "subtract", "multiply", "divide" */
23      private String operation = "add";
24      
25      /** Factor to be applied */
26      private double factor;
27      
28      public SimpleMathTransformer()
29      {
30          DataType<Number> numberDataType = DataTypeFactory.create(Number.class);
31          registerSourceType(numberDataType);
32          setReturnDataType(numberDataType);
33      }
34  
35      @Override
36      public Object doTransform(Object src, String outputEncoding) 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          // no auto-boxing
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  }