1 17 18 package org.apache.avalon.util.criteria; 19 20 import java.util.HashMap ; 21 22 29 public class Criteria extends HashMap 30 { 31 35 private final Parameter[] m_params; 36 37 41 42 46 public Criteria( final Parameter[] params ) 47 { 48 if( null == params ) 49 throw new NullPointerException ( "params" ); 50 m_params = params; 51 } 52 53 57 65 public Object put( final Object key, final Object value ) 66 { 67 if( !(key instanceof String )) 68 { 69 final String error = 70 "Invalid key: " + key; 71 throw new IllegalArgumentException ( error ); 72 } 73 74 Object current = super.get( key ); 75 76 if( null == value ) 77 { 78 super.put( key, null ); 79 return current; 80 } 81 82 final Parameter p = getParameter( (String ) key ); 83 84 try 85 { 86 final Object v = p.resolve( value ); 87 if( p.getParameterClass().isInstance( v ) ) 88 { 89 super.put( key, v ); 90 return current; 91 } 92 else 93 { 94 final String error = 95 "Resolved value: " + v 96 + " does not implement the parameter type: " 97 + p.getParameterClass(); 98 throw new IllegalArgumentException ( error ); 99 } 100 } 101 catch( Throwable e ) 102 { 103 final String error = 104 "Unable to assign a value to the key: " + key; 105 throw new CriteriaRuntimeException( error, e ); 106 } 107 } 108 109 113 public Object get( final Object key ) 114 { 115 Parameter param = getParameterFromObject( key ); 116 Object value = super.get( param.getKey() ); 117 if( null != value ) 118 { 119 return value; 120 } 121 else 122 { 123 return param.getDefault(); 124 } 125 } 126 127 131 135 protected Object getValue( final Parameter param ) 136 { 137 return get( param.getKey() ); 138 } 139 140 144 protected String [] getKeys() 145 { 146 return Parameter.getKeys( getParameters() ); 147 } 148 149 153 protected Parameter[] getParameters() 154 { 155 return m_params; 156 } 157 158 protected Parameter getParameter( final String key ) 159 { 160 Parameter[] params = getParameters(); 161 for( int i=0; i<params.length; i++ ) 162 { 163 Parameter parameter = params[i]; 164 if( parameter.getKey().equals( key ) ) return parameter; 165 } 166 167 final String error = 168 "Unknown key: [" + key + "]."; 169 throw new IllegalArgumentException ( error ); 170 } 171 172 private Parameter getParameterFromObject( Object key ) 173 { 174 if( key instanceof Parameter ) 175 { 176 return (Parameter) key; 177 } 178 else 179 { 180 return getParameter( key.toString() ); 181 } 182 } 183 184 185 } 186 | Popular Tags |