1 16 17 package org.springframework.mock.web.portlet; 18 19 import java.io.IOException ; 20 import java.util.Collections ; 21 import java.util.Enumeration ; 22 import java.util.HashSet ; 23 import java.util.Map ; 24 import java.util.Set ; 25 26 import javax.portlet.PortletPreferences; 27 import javax.portlet.PreferencesValidator; 28 import javax.portlet.ReadOnlyException; 29 import javax.portlet.ValidatorException; 30 31 import org.springframework.core.CollectionFactory; 32 import org.springframework.util.Assert; 33 34 41 public class MockPortletPreferences implements PortletPreferences { 42 43 private PreferencesValidator preferencesValidator; 44 45 private final Map preferences = CollectionFactory.createLinkedMapIfPossible(16); 46 47 private final Set readOnly = new HashSet (); 48 49 50 public void setReadOnly(String key, boolean readOnly) { 51 Assert.notNull(key, "Key must not be null"); 52 if (readOnly) { 53 this.readOnly.add(key); 54 } 55 else { 56 this.readOnly.remove(key); 57 } 58 } 59 60 public boolean isReadOnly(String key) { 61 Assert.notNull(key, "Key must not be null"); 62 return this.readOnly.contains(key); 63 } 64 65 public String getValue(String key, String def) { 66 Assert.notNull(key, "Key must not be null"); 67 String [] values = (String []) this.preferences.get(key); 68 return (values != null && values.length > 0 ? values[0] : def); 69 } 70 71 public String [] getValues(String key, String [] def) { 72 Assert.notNull(key, "Key must not be null"); 73 String [] values = (String []) this.preferences.get(key); 74 return (values != null && values.length > 0 ? values : def); 75 } 76 77 public void setValue(String key, String value) throws ReadOnlyException { 78 setValues(key, new String [] {value}); 79 } 80 81 public void setValues(String key, String [] values) throws ReadOnlyException { 82 Assert.notNull(key, "Key must not be null"); 83 if (isReadOnly(key)) { 84 throw new ReadOnlyException("Preference '" + key + "' is read-only"); 85 } 86 this.preferences.put(key, values); 87 } 88 89 public Enumeration getNames() { 90 return Collections.enumeration(this.preferences.keySet()); 91 } 92 93 public Map getMap() { 94 return Collections.unmodifiableMap(this.preferences); 95 } 96 97 public void reset(String key) throws ReadOnlyException { 98 Assert.notNull(key, "Key must not be null"); 99 if (isReadOnly(key)) { 100 throw new ReadOnlyException("Preference '" + key + "' is read-only"); 101 } 102 this.preferences.remove(key); 103 } 104 105 public void setPreferencesValidator(PreferencesValidator preferencesValidator) { 106 this.preferencesValidator = preferencesValidator; 107 } 108 109 public void store() throws IOException , ValidatorException { 110 if (this.preferencesValidator != null) { 111 this.preferencesValidator.validate(this); 112 } 113 } 114 115 } 116 | Popular Tags |