View Javadoc

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