View Javadoc

1   /*
2    * $Id: SimpleMathTransformer.java 11748 2008-05-14 07:17:24Z dirk.olmes $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSource, Inc.  All rights reserved.  http://www.mulesource.com
5    *
6    * The software in this package is published under the terms of the CPAL v1.0
7    * license, a copy of which has been included with this distribution in the
8    * LICENSE.txt file.
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   * A simple transformer which adds/subtracts/multiplies/divides a constant factor to numeric messages. 
21   */
22  public class SimpleMathTransformer extends AbstractTransformer 
23  {
24      /** Operation to perform: "add", "subtract", "multiply", "divide" */
25      private String operation = "add";
26      
27      /** Factor to be applied */
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          // 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  }