View Javadoc

1   /*
2    * $Id: AccumulatorComponent.java 19191 2010-08-25 21:05:23Z tcarlson $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.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.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   * Component which accumulates successive numbers, by adding/subtracting/multiplying/dividing.  
22   */
23  public class AccumulatorComponent implements Callable
24  {
25      /** Operation to perform: "add", "subtract", "multiply", "divide" */
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.getMessage().getPayload();
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          // no auto-boxing
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  }