001/** 002 * Copyright 2010-2014 The Kuali Foundation 003 * 004 * Licensed under the Educational Community License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.opensource.org/licenses/ecl2.php 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package org.kuali.common.util.xml.jaxb.adapter; 017 018import java.util.List; 019 020import javax.xml.bind.annotation.adapters.XmlAdapter; 021 022import org.apache.commons.lang3.StringUtils; 023import org.kuali.common.util.Assert; 024import org.kuali.common.util.CollectionUtils; 025 026import com.google.common.collect.ImmutableList; 027 028/** 029 * Trim each element from List<String> to create the CSV when going from Object -> XML.<br> 030 * Convert the CSV back into List<String> when going from XML -> Object.<br> 031 * The List<String> returned when going from XML -> Object is immutable.</br> 032 * 033 * @throws NullPointerException 034 * If the list is null or any strings in the list are null 035 * @throws IllegalArgumentException 036 * If any strings in the list contain a comma 037 */ 038public class TrimmingCSVStringAdapter extends XmlAdapter<String, List<String>> { 039 040 private static final String DELIMITER = ","; 041 042 @Override 043 public final String marshal(List<String> strings) { 044 if (strings.size() == 0) { 045 return null; 046 } 047 StringBuilder sb = new StringBuilder(); 048 for (int i = 0; i < strings.size(); i++) { 049 if (i != 0) { 050 sb.append(DELIMITER); 051 } 052 String trimmed = strings.get(i).trim(); 053 Assert.isFalse(StringUtils.contains(trimmed, DELIMITER), "[" + trimmed + "] contains '" + DELIMITER + "'"); 054 sb.append(trimmed); 055 } 056 return sb.toString(); 057 } 058 059 @Override 060 public final List<String> unmarshal(String string) { 061 if (string == null) { 062 return ImmutableList.of(); 063 } else { 064 return ImmutableList.copyOf(CollectionUtils.getTrimmedListFromCSV(string)); 065 } 066 } 067 068}