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.transformer.simple;
8   
9   import org.mule.api.transformer.DiscoverableTransformer;
10  import org.mule.api.transformer.TransformerException;
11  import org.mule.transformer.AbstractTransformer;
12  import org.mule.transformer.types.DataTypeFactory;
13  import org.mule.transformer.types.SimpleDataType;
14  
15  import java.text.NumberFormat;
16  
17  /**
18   * <code>NumberToString</code> converts a Number to a String.  A NumberFormat is used if one is provided.
19   */
20  public class NumberToString extends AbstractTransformer implements DiscoverableTransformer
21  {
22  
23      private NumberFormat numberFormat;
24  
25      /**
26       * Give core transformers a slighty higher priority
27       */
28      private int priorityWeighting = DiscoverableTransformer.DEFAULT_PRIORITY_WEIGHTING + 1;
29  
30      public NumberToString()
31      {
32          registerSourceType(new SimpleDataType<Object>(Number.class));
33          setReturnDataType(DataTypeFactory.STRING);
34      }
35  
36      public NumberToString(NumberFormat numberFormat)
37      {
38          this();
39          this.numberFormat = numberFormat;
40      }
41  
42      @Override
43      public Object doTransform(Object src, String encoding) throws TransformerException
44      {
45          if (src == null)
46          {
47              return "";
48          }
49  
50          if (numberFormat != null)
51          {
52              return numberFormat.format(src);
53          }
54          else
55          {
56              return ((Number) src).toString();
57          }
58      }
59  
60      public int getPriorityWeighting()
61      {
62          return priorityWeighting;
63      }
64  
65      public void setPriorityWeighting(int priorityWeighting)
66      {
67          this.priorityWeighting = priorityWeighting;
68      }
69  
70  }