View Javadoc

1   /*
2    * $Id: ObjectToString.java 7976 2007-08-21 14:26:13Z 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.transformers.simple;
12  
13  import org.mule.transformers.AbstractTransformer;
14  import org.mule.umo.transformer.TransformerException;
15  
16  import java.util.Collection;
17  import java.util.Iterator;
18  import java.util.Map;
19  
20  /**
21   * <code>ObjectToString</code> transformer is useful for debugging. It will return
22   * human-readable output for various kinds of objects. Right now, it is just coded to
23   * handle Map and Collection objects. Others will be added.
24   */
25  public class ObjectToString extends AbstractTransformer
26  {
27      protected static final int DEFAULT_BUFFER_SIZE = 80;
28  
29      public ObjectToString()
30      {
31          registerSourceType(Object.class);
32          setReturnClass(String.class);
33      }
34  
35      public Object doTransform(Object src, String encoding) throws TransformerException
36      {
37          String output = "";
38  
39          if (src instanceof Map)
40          {
41              Iterator iter = ((Map) src).entrySet().iterator();
42              if (iter.hasNext())
43              {
44                  StringBuffer b = new StringBuffer(DEFAULT_BUFFER_SIZE);
45                  while (iter.hasNext())
46                  {
47                      Map.Entry e = (Map.Entry) iter.next();
48                      Object key = e.getKey();
49                      Object value = e.getValue();
50                      b.append(key.toString()).append(':').append(value.toString());
51                      if (iter.hasNext())
52                      {
53                          b.append('|');
54                      }
55                  }
56                  output = b.toString();
57              }
58          }
59          else if (src instanceof Collection)
60          {
61              Iterator iter = ((Collection) src).iterator();
62              if (iter.hasNext())
63              {
64                  StringBuffer b = new StringBuffer(DEFAULT_BUFFER_SIZE);
65                  while (iter.hasNext())
66                  {
67                      b.append(iter.next().toString());
68                      if (iter.hasNext())
69                      {
70                          b.append('|');
71                      }
72                  }
73                  output = b.toString();
74              }
75          }
76          else
77          {
78              output = src.toString();
79          }
80  
81          return output;
82      }
83  
84  }