View Javadoc

1   /*
2    * $Id: ByteArrayToHexString.java 11336 2008-03-12 17:53:18Z 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.simple;
12  
13  import org.mule.api.transformer.TransformerException;
14  import org.mule.transformer.AbstractTransformer;
15  import org.mule.util.IOUtils;
16  import org.mule.util.StringUtils;
17  
18  import java.io.InputStream;
19  
20  
21  /**
22   * Converts a Byte array to a Hex String.
23   */
24  public class ByteArrayToHexString extends AbstractTransformer
25  {
26      private volatile boolean upperCase = false;
27  
28      public ByteArrayToHexString()
29      {
30          registerSourceType(byte[].class);
31          registerSourceType(InputStream.class);
32          setReturnClass(String.class);
33      }
34  
35      public boolean getUpperCase()
36      {
37          return upperCase;
38      }
39  
40      public void setUpperCase(boolean value)
41      {
42          upperCase = value;
43      }
44  
45      protected Object doTransform(Object src, String encoding) throws TransformerException
46      {
47          if (src == null)
48          {
49              return StringUtils.EMPTY;
50          }
51  
52          try
53          {
54              byte[] bytes = null;
55              if (src instanceof InputStream)
56              {
57                  InputStream input = (InputStream) src;
58                  try
59                  {
60                      bytes = IOUtils.toByteArray(input);
61                  }
62                  finally
63                  {
64                      IOUtils.closeQuietly(input);
65                  }
66              }
67              else
68              {
69                  bytes = (byte[]) src;
70              }
71                  
72              return StringUtils.toHexString(bytes, upperCase);
73          }
74          catch (Exception ex)
75          {
76              throw new TransformerException(this, ex);
77          }
78      }
79  
80  }