1 9 package org.jboss.portal.common.value; 10 11 12 import java.util.Arrays ; 13 import java.util.List ; 14 15 19 public abstract class AbstractValues implements Value 20 { 21 22 23 private int hashCode = 0; 24 25 28 protected abstract Object [] getObjects(); 29 30 public int asInt() throws NullConversionException, FormatConversionException 31 { 32 int[] tmp = asIntArray(); 33 if (tmp.length == 0) 34 { 35 throw new NullConversionException(); 36 } 37 return tmp[0]; 38 } 39 40 public boolean asBoolean() throws NullConversionException, FormatConversionException 41 { 42 boolean[] tmp = asBooleanArray(); 43 if (tmp.length == 0) 44 { 45 throw new NullConversionException(); 46 } 47 return tmp[0]; 48 } 49 50 public boolean isNull() 51 { 52 return getObjects().length == 0 || getObjects()[0] == null; 53 } 54 55 public boolean isMultiValued() 56 { 57 return getObjects().length > 1; 58 } 59 60 63 public int[] asIntArray() throws NullConversionException, FormatConversionException 64 { 65 throw new FormatConversionException(); 66 } 67 68 71 public boolean[] asBooleanArray() throws NullConversionException, FormatConversionException 72 { 73 throw new FormatConversionException(); 74 } 75 76 public int hashCode() 77 { 78 if (isNull()) 79 { 80 return 0; 81 } 82 else 83 { 84 if (hashCode == 0) 85 { 86 Object [] objects = getObjects(); 87 for (int i = 0;i < objects.length;i++) 88 { 89 Object o = objects[i]; 90 if (o != null) 91 { 92 hashCode *= 43 + o.hashCode(); 93 } 94 } 95 } 96 else 97 { 98 return hashCode; 99 } 100 } 101 return hashCode; 102 } 103 104 public boolean equals(Object obj) 105 { 106 if (obj == this) 107 { 108 return true; 109 } 110 if (obj.getClass().equals(getClass())) 111 { 112 AbstractValues other = (AbstractValues)obj; 113 switch ((other.isNull() ? 2 : 0) + (isNull() ? 1 : 0)) 114 { 115 case 1: 116 case 2: 117 return false; 118 case 3: 119 return true; 120 } 121 return Arrays.equals(getObjects(), other.getObjects()); 122 } 123 return false; 124 } 125 126 public Object [] asObjectArray() 127 { 128 if (isNull()) 129 { 130 return Helper.EMPTY_OBJECT_ARRAY; 131 } 132 return getObjects(); 133 } 134 135 public Object asObject() 136 { 137 if (isNull()) 138 { 139 return null; 140 } 141 return getObjects()[0]; 142 } 143 144 public List asObjectList() 145 { 146 Object [] values = asObjectArray(); 147 return Arrays.asList(values); 148 } 149 150 public String toString() 151 { 152 StringBuffer buffer = new StringBuffer ("["); 153 String [] strings = asStringArray(); 154 for (int i = 0;i < strings.length;i++) 155 { 156 String s = strings[i]; 157 buffer.append(i > 0 ? "," : ""). 158 append(String.valueOf(s)); 159 } 160 buffer.append("]"); 161 return buffer.toString(); 162 } 163 } 164 | Popular Tags |