View Javadoc
1   /*
2    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
3    * The software in this package is published under the terms of the CPAL v1.0
4    * license, a copy of which has been included with this distribution in the
5    * LICENSE.txt file.
6    */
7   package org.mule.transformer.simple;
8   
9   import org.mule.api.transformer.TransformerException;
10  import org.mule.transformer.AbstractTransformer;
11  import org.mule.transformer.types.DataTypeFactory;
12  import org.mule.util.IOUtils;
13  import org.mule.util.StringUtils;
14  
15  import java.io.InputStream;
16  
17  
18  /**
19   * Converts a Byte array to a Hex String.
20   */
21  public class ByteArrayToHexString extends AbstractTransformer
22  {
23      private volatile boolean upperCase = false;
24  
25      public ByteArrayToHexString()
26      {
27          registerSourceType(DataTypeFactory.BYTE_ARRAY);
28          registerSourceType(DataTypeFactory.INPUT_STREAM);
29          setReturnDataType(DataTypeFactory.TEXT_STRING);
30      }
31  
32      public boolean getUpperCase()
33      {
34          return upperCase;
35      }
36  
37      public void setUpperCase(boolean value)
38      {
39          upperCase = value;
40      }
41  
42      @Override
43      protected Object doTransform(Object src, String encoding) throws TransformerException
44      {
45          if (src == null)
46          {
47              return StringUtils.EMPTY;
48          }
49  
50          try
51          {
52              byte[] bytes = null;
53              if (src instanceof InputStream)
54              {
55                  InputStream input = (InputStream) src;
56                  try
57                  {
58                      bytes = IOUtils.toByteArray(input);
59                  }
60                  finally
61                  {
62                      IOUtils.closeQuietly(input);
63                  }
64              }
65              else
66              {
67                  bytes = (byte[]) src;
68              }
69                  
70              return StringUtils.toHexString(bytes, upperCase);
71          }
72          catch (Exception ex)
73          {
74              throw new TransformerException(this, ex);
75          }
76      }
77  
78  }