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.config.converters;
8   
9   import org.mule.api.MuleContext;
10  import org.mule.api.expression.PropertyConverter;
11  import org.mule.util.StringUtils;
12  
13  import java.util.Properties;
14  import java.util.StringTokenizer;
15  
16  /**
17   * Converts a comma-separated list of key/value pairs, e.g.,
18   * <code>"apple=green, banana=yellow"</code> into a {@link java.util.Properties} map.
19   * Property placeholders can be used in these values:
20   * <code>"apple=${apple.color}, banana=yellow"</code> 
21   */
22  public class PropertiesConverter implements PropertyConverter
23  {
24      public static final String DELIM = ",";
25  
26      public Object convert(String properties, MuleContext context)
27      {
28          if (StringUtils.isNotBlank(properties))
29          {
30              Properties props = new Properties();
31              
32              StringTokenizer st = new StringTokenizer(properties, DELIM);
33              while (st.hasMoreTokens())
34              {
35                  String key = st.nextToken().trim();
36                  int i = key.indexOf("=");
37                  if(i < 1) {
38                      throw new IllegalArgumentException("Property string is malformed: " + properties);
39                  }
40                  String value = key.substring(i+1);
41                  key = key.substring(0, i);
42                  props.setProperty(key, value);
43              }
44              return props;
45          }
46         return null;
47      }
48  
49      public Class getType()
50      {
51          return Properties.class;
52      }
53  }