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.transport.http.transformers;
8   
9   import org.mule.api.MuleMessage;
10  import org.mule.api.transformer.TransformerException;
11  import org.mule.transformer.AbstractMessageTransformer;
12  
13  import java.net.URLDecoder;
14  import java.util.ArrayList;
15  import java.util.HashMap;
16  import java.util.List;
17  import java.util.Map;
18  import java.util.StringTokenizer;
19  
20  /**
21   * Converts HTML forms POSTs into a Map of parameters. Each key can have multiple
22   * values, in which case the value will be a List<String>. Otherwise, it will
23   * be a String.
24   */
25  public class FormTransformer extends AbstractMessageTransformer
26  {
27  
28      @Override
29      public Object transformMessage(MuleMessage message, String outputEncoding) throws TransformerException
30      {
31          try
32          {
33              String v = message.getPayloadAsString();
34              Map<String, Object> values = new HashMap<String, Object>();
35  
36              final StringTokenizer tokenizer = new StringTokenizer(v, "&");
37              String token;
38              while (tokenizer.hasMoreTokens())
39              {
40                  token = tokenizer.nextToken();
41                  int idx = token.indexOf('=');
42                  if (idx < 0)
43                  {
44                      add(values, URLDecoder.decode(token, outputEncoding), null);
45                  }
46                  else if (idx > 0)
47                  {
48                      add(values, URLDecoder.decode(token.substring(0, idx), outputEncoding),
49                          URLDecoder.decode(token.substring(idx + 1), outputEncoding));
50                  }
51              }
52              return values;
53          }
54          catch (Exception e)
55          {
56              throw new TransformerException(this, e);
57          }
58      }
59  
60      @SuppressWarnings("unchecked")
61      private void add(Map<String, Object> values, String key, String value)
62      {
63          Object existingValue = values.get(key);
64          if (existingValue == null)
65          {
66              values.put(key, value);
67          }
68          else if (existingValue instanceof List)
69          {
70              List<String> list = (List<String>)existingValue;
71              list.add(value);
72          }
73          else if (existingValue instanceof String)
74          {
75              List<String> list = new ArrayList<String>();
76              list.add((String)existingValue);
77              list.add(value);
78              values.put(key, list);
79          }
80      }
81  }