View Javadoc

1   package org.kuali.common.util.xml.jaxb.adapter;
2   
3   import java.util.List;
4   
5   import javax.xml.bind.annotation.adapters.XmlAdapter;
6   
7   import org.apache.commons.lang3.StringUtils;
8   import org.kuali.common.util.Assert;
9   import org.kuali.common.util.CollectionUtils;
10  
11  import com.google.common.collect.ImmutableList;
12  
13  /**
14   * Trim each element from List&lt;String> to create the CSV when going from Object -> XML.<br>
15   * Convert the CSV back into List&lt;String> when going from XML -> Object.<br>
16   * The List&lt;String> returned when going from XML -> Object is immutable.</br>
17   * 
18   * @throws NullPointerException
19   *             If the list is null or any strings in the list are null
20   * @throws IllegalArgumentException
21   *             If any strings in the list contain a comma
22   */
23  public class TrimmingCSVStringAdapter extends XmlAdapter<String, List<String>> {
24  
25  	private static final String DELIMITER = ",";
26  
27  	@Override
28  	public final String marshal(List<String> strings) {
29  		if (strings.size() == 0) {
30  			return null;
31  		}
32  		StringBuilder sb = new StringBuilder();
33  		for (int i = 0; i < strings.size(); i++) {
34  			if (i != 0) {
35  				sb.append(DELIMITER);
36  			}
37  			String trimmed = strings.get(i).trim();
38  			Assert.isFalse(StringUtils.contains(trimmed, DELIMITER), "[" + trimmed + "] contains '" + DELIMITER + "'");
39  			sb.append(trimmed);
40  		}
41  		return sb.toString();
42  	}
43  
44  	@Override
45  	public final List<String> unmarshal(String string) {
46  		if (string == null) {
47  			return ImmutableList.<String> of();
48  		} else {
49  			return ImmutableList.copyOf(CollectionUtils.getTrimmedListFromCSV(string));
50  		}
51  	}
52  
53  }