001package org.kuali.common.util.xml.jaxb.adapter;
002
003import java.util.List;
004
005import javax.xml.bind.annotation.adapters.XmlAdapter;
006
007import org.apache.commons.lang3.StringUtils;
008import org.kuali.common.util.Assert;
009import org.kuali.common.util.CollectionUtils;
010
011import com.google.common.collect.ImmutableList;
012
013/**
014 * Trim each element from List&lt;String> to create the CSV when going from Object -> XML.<br>
015 * Convert the CSV back into List&lt;String> when going from XML -> Object.<br>
016 * The List&lt;String> returned when going from XML -> Object is immutable.</br>
017 * 
018 * @throws NullPointerException
019 *             If the list is null or any strings in the list are null
020 * @throws IllegalArgumentException
021 *             If any strings in the list contain a comma
022 */
023public class TrimmingCSVStringAdapter extends XmlAdapter<String, List<String>> {
024
025        private static final String DELIMITER = ",";
026
027        @Override
028        public final String marshal(List<String> strings) {
029                if (strings.size() == 0) {
030                        return null;
031                }
032                StringBuilder sb = new StringBuilder();
033                for (int i = 0; i < strings.size(); i++) {
034                        if (i != 0) {
035                                sb.append(DELIMITER);
036                        }
037                        String trimmed = strings.get(i).trim();
038                        Assert.isFalse(StringUtils.contains(trimmed, DELIMITER), "[" + trimmed + "] contains '" + DELIMITER + "'");
039                        sb.append(trimmed);
040                }
041                return sb.toString();
042        }
043
044        @Override
045        public final List<String> unmarshal(String string) {
046                if (string == null) {
047                        return ImmutableList.of();
048                } else {
049                        return ImmutableList.copyOf(CollectionUtils.getTrimmedListFromCSV(string));
050                }
051        }
052
053}