View Javadoc

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