View Javadoc

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