001 /* 002 * Created on Dec 26, 2003 003 */ 004 package net.sf.jolene.html; 005 006 import java.util.*; 007 008 009 /** 010 * Map wrapper to handle html attributes. It's a case insensitive sorted map. 011 * 012 * @author Dan Howard 013 */ 014 public class Attributes implements IAttributes { 015 016 private SortedMap<String, String> attributes; 017 018 /** 019 * 020 */ 021 public Attributes() { 022 attributes = new TreeMap<String, String>(); 023 } 024 025 /** 026 * Sets an attribute. 027 * 028 * @param key - attribute name 029 * @param value - attribute value 030 * @return String 031 */ 032 public String setAttribute(String key, String value) { 033 // Don't allow null values 034 if (value == null) { 035 value = ""; 036 } 037 return attributes.put(key.toLowerCase(), value); 038 } 039 040 /** 041 * Gets an attribute from the attribute map or NULL if not found. 042 * 043 * @param key - attribute name 044 * @return String or NULL of key is null or not found 045 */ 046 public String getAttribute(String key) { 047 if (key == null) { 048 return null; 049 } 050 return attributes.get(key.toLowerCase()); 051 } 052 053 /** 054 * Remove an attribute. 055 * 056 * @param key - attribute name 057 * @return String 058 */ 059 public String removeAttribute(String key) { 060 return attributes.remove(key.toLowerCase()); 061 } 062 063 /** 064 * Indicates whether or not an attribute exists. 065 * 066 * @param key - attribute name 067 * @return boolean 068 */ 069 public boolean hasAttribute(String key) { 070 if (key == null) { 071 return false; 072 } 073 return getAttribute(key.toLowerCase()) != null; 074 } 075 076 /** 077 * Returns the attributes as a Set. 078 * 079 * @return Set 080 */ 081 public Set<String> keySet() { 082 return attributes.keySet(); 083 } 084 085 /** 086 * Returns the attribute values as a Collection. 087 * 088 * @return Collection 089 */ 090 public Collection<String> values() { 091 return attributes.values(); 092 } 093 094 095 /** 096 * Clears the attributes. 097 */ 098 public void clear() { 099 attributes.clear(); 100 } 101 102 @Override 103 public String toString() { 104 Iterator<String> it = keySet().iterator(); 105 StringBuilder s = new StringBuilder(""); 106 while (it.hasNext()) { 107 String key = it.next(); 108 s.append(key).append('=').append(getAttribute(key)).append(' '); 109 } 110 return s.toString(); 111 } 112 }