1 16 17 package org.springframework.core.io.support; 18 19 import java.beans.PropertyEditorSupport ; 20 import java.io.IOException ; 21 import java.util.ArrayList ; 22 import java.util.Arrays ; 23 import java.util.Collection ; 24 import java.util.Iterator ; 25 import java.util.List ; 26 27 import org.springframework.core.io.Resource; 28 import org.springframework.util.SystemPropertyUtils; 29 30 51 public class ResourceArrayPropertyEditor extends PropertyEditorSupport { 52 53 private final ResourcePatternResolver resourcePatternResolver; 54 55 56 61 public ResourceArrayPropertyEditor() { 62 this.resourcePatternResolver = new PathMatchingResourcePatternResolver(); 63 } 64 65 69 public ResourceArrayPropertyEditor(ResourcePatternResolver resourcePatternResolver) { 70 this.resourcePatternResolver = resourcePatternResolver; 71 } 72 73 74 77 public void setAsText(String text) { 78 String pattern = resolvePath(text).trim(); 79 try { 80 setValue(this.resourcePatternResolver.getResources(pattern)); 81 } 82 catch (IOException ex) { 83 throw new IllegalArgumentException ( 84 "Could not resolve resource location pattern [" + pattern + "]: " + ex.getMessage()); 85 } 86 } 87 88 92 public void setValue(Object value) throws IllegalArgumentException { 93 if (value instanceof Collection || (value instanceof Object [] && !(value instanceof Resource[]))) { 94 Collection input = (value instanceof Collection ? (Collection ) value : Arrays.asList((Object []) value)); 95 List merged = new ArrayList (); 96 for (Iterator it = input.iterator(); it.hasNext();) { 97 Object element = it.next(); 98 if (element instanceof String ) { 99 String pattern = resolvePath((String ) element).trim(); 102 try { 103 Resource[] resources = this.resourcePatternResolver.getResources(pattern); 104 for (int i = 0; i < resources.length; i++) { 105 Resource resource = resources[i]; 106 if (!merged.contains(resource)) { 107 merged.add(resource); 108 } 109 } 110 } 111 catch (IOException ex) { 112 throw new IllegalArgumentException ( 113 "Could not resolve resource location pattern [" + pattern + "]: " + ex.getMessage()); 114 } 115 } 116 else if (element instanceof Resource) { 117 if (!merged.contains(element)) { 119 merged.add(element); 120 } 121 } 122 else { 123 throw new IllegalArgumentException ("Cannot convert element [" + element + "] to [" + 124 Resource.class.getName() + "]: only location String and Resource object supported"); 125 } 126 } 127 super.setValue(merged.toArray(new Resource[merged.size()])); 128 } 129 130 else { 131 super.setValue(value); 134 } 135 } 136 137 144 protected String resolvePath(String path) { 145 return SystemPropertyUtils.resolvePlaceholders(path); 146 } 147 148 } 149 | Popular Tags |