View Javadoc

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