View Javadoc

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