View Javadoc

1   /*
2    * $Id: XmlEntityEncoder.java 7976 2007-08-21 14:26:13Z 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.transformers.codec;
12  
13  import org.mule.config.i18n.CoreMessages;
14  import org.mule.transformers.AbstractTransformer;
15  import org.mule.umo.transformer.TransformerException;
16  import org.mule.util.XMLEntityCodec;
17  
18  /**
19   * Encodes a string with XML entities
20   */
21  public class XmlEntityEncoder extends AbstractTransformer
22  {
23  
24      public XmlEntityEncoder()
25      {
26          registerSourceType(String.class);
27          registerSourceType(byte[].class);
28          setReturnClass(String.class);
29      }
30  
31      public Object doTransform(Object src, String encoding) throws TransformerException
32      {
33          try
34          {
35              String data;
36  
37              if (src instanceof byte[])
38              {
39                  data = new String((byte[]) src, encoding);
40              }
41              else
42              {
43                  data = (String) src;
44              }
45  
46              return XMLEntityCodec.encodeString(data);
47          }
48          catch (Exception ex)
49          {
50              throw new TransformerException(
51                  CoreMessages.transformFailed(src.getClass().getName(), "XML"), 
52                  this, ex);
53          }
54      }
55  
56  }