01: /*
02:
03: This software is OSI Certified Open Source Software.
04: OSI Certified is a certification mark of the Open Source Initiative.
05:
06: The license (Mozilla version 1.0) can be read at the MMBase site.
07: See http://www.MMBase.org/license
08:
09: */
10: package org.mmbase.util;
11:
12: import java.util.*;
13:
14: /**
15: * Utility class for splitting delimited values.
16: *
17: * @author Pierre van Rooden
18: * @author Kees Jongenburger
19: * @author Michiel Meeuwissen
20: * @version $Id: StringSplitter.java,v 1.10 2007/02/11 19:21:11 nklasens Exp $
21: */
22: public class StringSplitter {
23:
24: /**
25: * Simple util method to split delimited values to a list. Useful for attributes.
26: * Similar to <code>String.split()</code>, but returns a List instead of an array, and trims the values.
27: * @param string the string to split
28: * @param delimiter
29: * @return a (modifiable) List containing the elements
30: */
31: static public List<String> split(String string, String delimiter) {
32: List<String> result = new ArrayList<String>();
33: if (string == null)
34: return result;
35: for (String v : string.split(delimiter)) {
36: result.add(v.trim());
37: }
38: return result;
39: }
40:
41: /**
42: * Simple util method to split comma separated values.
43: * @see #split(String, String)
44: * @param string the string to split
45: * @return a List containing the elements
46: */
47: static public List<String> split(String string) {
48: return split(string, ",");
49: }
50:
51: /**
52: * Splits up a String, (using comma delimiter), but takes into account brackets. So
53: * a(b,c,d),e,f(g) will be split up in a(b,c,d) and e and f(g).
54: * @since MMBase-1.8
55: */
56: static public List<String> splitFunctions(CharSequence attribute) {
57: int commaPos = 0;
58: int nested = 0;
59: List<String> result = new ArrayList<String>();
60: int i;
61: int length = attribute.length();
62: for (i = 0; i < length; i++) {
63: char c = attribute.charAt(i);
64: if ((c == ',') || (c == ';')) {
65: if (nested == 0) {
66: result.add(attribute.subSequence(commaPos, i)
67: .toString().trim());
68: commaPos = i + 1;
69: }
70: } else if (c == '(') {
71: nested++;
72: } else if (c == ')') {
73: nested--;
74: }
75: }
76: if (i > 0) {
77: result.add(attribute.toString().substring(commaPos).trim());
78: }
79: return result;
80: }
81:
82: /**
83: * @since MMBase-1.9
84: */
85:
86: static public Map<String, String> map(String string) {
87: Map<String, String> map = new HashMap<String, String>();
88: List<String> keyValues = split(string);
89: for (String kv : keyValues) {
90: if ("".equals(kv))
91: continue;
92: int is = kv.indexOf('=');
93: map.put(kv.substring(0, is), kv.substring(is + 1));
94: }
95: return map;
96: }
97:
98: }
|