001// Copyright 2006, 2007, 2008, 2010, 2012 The Apache Software Foundation 002// 003// Licensed under the Apache License, Version 2.0 (the "License"); 004// you may not use this file except in compliance with the License. 005// You may obtain a copy of the License at 006// 007// http://www.apache.org/licenses/LICENSE-2.0 008// 009// Unless required by applicable law or agreed to in writing, software 010// distributed under the License is distributed on an "AS IS" BASIS, 011// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 012// See the License for the specific language governing permissions and 013// limitations under the License. 014 015package org.apache.tapestry5.ioc.internal.services; 016 017import org.apache.tapestry5.func.F; 018import org.apache.tapestry5.ioc.internal.util.CollectionFactory; 019import org.apache.tapestry5.ioc.internal.util.InheritanceSearch; 020import org.apache.tapestry5.ioc.internal.util.InternalUtils; 021import org.apache.tapestry5.ioc.internal.util.LockSupport; 022import org.apache.tapestry5.ioc.services.Coercion; 023import org.apache.tapestry5.ioc.services.CoercionTuple; 024import org.apache.tapestry5.ioc.services.TypeCoercer; 025import org.apache.tapestry5.ioc.util.AvailableValues; 026import org.apache.tapestry5.ioc.util.UnknownValueException; 027import org.apache.tapestry5.plastic.PlasticUtils; 028import org.apache.tapestry5.util.StringToEnumCoercion; 029 030import java.util.*; 031 032@SuppressWarnings("all") 033public class TypeCoercerImpl extends LockSupport implements TypeCoercer 034{ 035 // Constructed from the service's configuration. 036 037 private final Map<Class, List<CoercionTuple>> sourceTypeToTuple = CollectionFactory.newMap(); 038 039 /** 040 * A coercion to a specific target type. Manages a cache of coercions to specific types. 041 */ 042 private class TargetCoercion 043 { 044 private final Class type; 045 046 private final Map<Class, Coercion> cache = CollectionFactory.newConcurrentMap(); 047 048 TargetCoercion(Class type) 049 { 050 this.type = type; 051 } 052 053 void clearCache() 054 { 055 cache.clear(); 056 } 057 058 Object coerce(Object input) 059 { 060 Class sourceType = input != null ? input.getClass() : Void.class; 061 062 if (type.isAssignableFrom(sourceType)) 063 { 064 return input; 065 } 066 067 Coercion c = getCoercion(sourceType); 068 069 try 070 { 071 return type.cast(c.coerce(input)); 072 } catch (Exception ex) 073 { 074 throw new RuntimeException(ServiceMessages.failedCoercion(input, type, c, ex), ex); 075 } 076 } 077 078 String explain(Class sourceType) 079 { 080 return getCoercion(sourceType).toString(); 081 } 082 083 private Coercion getCoercion(Class sourceType) 084 { 085 Coercion c = cache.get(sourceType); 086 087 if (c == null) 088 { 089 c = findOrCreateCoercion(sourceType, type); 090 cache.put(sourceType, c); 091 } 092 093 return c; 094 } 095 } 096 097 /** 098 * Map from a target type to a TargetCoercion for that type. 099 */ 100 private final Map<Class, TargetCoercion> typeToTargetCoercion = new WeakHashMap<Class, TargetCoercion>(); 101 102 private static final Coercion NO_COERCION = new Coercion<Object, Object>() 103 { 104 public Object coerce(Object input) 105 { 106 return input; 107 } 108 }; 109 110 private static final Coercion COERCION_NULL_TO_OBJECT = new Coercion<Void, Object>() 111 { 112 public Object coerce(Void input) 113 { 114 return null; 115 } 116 117 @Override 118 public String toString() 119 { 120 return "null --> null"; 121 } 122 }; 123 124 public TypeCoercerImpl(Collection<CoercionTuple> tuples) 125 { 126 for (CoercionTuple tuple : tuples) 127 { 128 Class key = tuple.getSourceType(); 129 130 InternalUtils.addToMapList(sourceTypeToTuple, key, tuple); 131 } 132 } 133 134 @SuppressWarnings("unchecked") 135 public Object coerce(Object input, Class targetType) 136 { 137 assert targetType != null; 138 139 Class effectiveTargetType = PlasticUtils.toWrapperType(targetType); 140 141 if (effectiveTargetType.isInstance(input)) 142 { 143 return input; 144 } 145 146 147 return getTargetCoercion(effectiveTargetType).coerce(input); 148 } 149 150 @SuppressWarnings("unchecked") 151 public <S, T> Coercion<S, T> getCoercion(Class<S> sourceType, Class<T> targetType) 152 { 153 assert sourceType != null; 154 assert targetType != null; 155 156 Class effectiveSourceType = PlasticUtils.toWrapperType(sourceType); 157 Class effectiveTargetType = PlasticUtils.toWrapperType(targetType); 158 159 if (effectiveTargetType.isAssignableFrom(effectiveSourceType)) 160 { 161 return NO_COERCION; 162 } 163 164 return getTargetCoercion(effectiveTargetType).getCoercion(effectiveSourceType); 165 } 166 167 @SuppressWarnings("unchecked") 168 public <S, T> String explain(Class<S> sourceType, Class<T> targetType) 169 { 170 assert sourceType != null; 171 assert targetType != null; 172 173 Class effectiveTargetType = PlasticUtils.toWrapperType(targetType); 174 Class effectiveSourceType = PlasticUtils.toWrapperType(sourceType); 175 176 // Is a coercion even necessary? Not if the target type is assignable from the 177 // input value. 178 179 if (effectiveTargetType.isAssignableFrom(effectiveSourceType)) 180 { 181 return ""; 182 } 183 184 return getTargetCoercion(effectiveTargetType).explain(effectiveSourceType); 185 } 186 187 private TargetCoercion getTargetCoercion(Class targetType) 188 { 189 try 190 { 191 acquireReadLock(); 192 193 TargetCoercion tc = typeToTargetCoercion.get(targetType); 194 195 return tc != null ? tc : createAndStoreNewTargetCoercion(targetType); 196 } finally 197 { 198 releaseReadLock(); 199 } 200 } 201 202 private TargetCoercion createAndStoreNewTargetCoercion(Class targetType) 203 { 204 try 205 { 206 upgradeReadLockToWriteLock(); 207 208 // Inner check since some other thread may have beat us to it. 209 210 TargetCoercion tc = typeToTargetCoercion.get(targetType); 211 212 if (tc == null) 213 { 214 tc = new TargetCoercion(targetType); 215 typeToTargetCoercion.put(targetType, tc); 216 } 217 218 return tc; 219 } finally 220 { 221 downgradeWriteLockToReadLock(); 222 } 223 } 224 225 public void clearCache() 226 { 227 try 228 { 229 acquireReadLock(); 230 231 // There's no need to clear the typeToTargetCoercion map, as it is a WeakHashMap and 232 // will release the keys for classes that are no longer in existence. On the other hand, 233 // there's likely all sorts of references to unloaded classes inside each TargetCoercion's 234 // individual cache, so clear all those. 235 236 for (TargetCoercion tc : typeToTargetCoercion.values()) 237 { 238 // Can tc ever be null? 239 240 tc.clearCache(); 241 } 242 } finally 243 { 244 releaseReadLock(); 245 } 246 } 247 248 /** 249 * Here's the real meat; we do a search of the space to find coercions, or a system of 250 * coercions, that accomplish 251 * the desired coercion. 252 * <p/> 253 * There's <strong>TREMENDOUS</strong> room to improve this algorithm. For example, inheritance lists could be 254 * cached. Further, there's probably more ways to early prune the search. However, even with dozens or perhaps 255 * hundreds of tuples, I suspect the search will still grind to a conclusion quickly. 256 * <p/> 257 * The order of operations should help ensure that the most efficient tuple chain is located. If you think about how 258 * tuples are added to the queue, there are two factors: size (the number of steps in the coercion) and 259 * "class distance" (that is, number of steps up the inheritance hiearchy). All the appropriate 1 step coercions 260 * will be considered first, in class distance order. Along the way, we'll queue up all the 2 step coercions, again 261 * in class distance order. By the time we reach some of those, we'll have begun queueing up the 3 step coercions, and 262 * so forth, until we run out of input tuples we can use to fabricate multi-step compound coercions, or reach a 263 * final response. 264 * <p/> 265 * This does create a good number of short lived temporary objects (the compound tuples), but that's what the GC is 266 * really good at. 267 * 268 * @param sourceType 269 * @param targetType 270 * @return coercer from sourceType to targetType 271 */ 272 @SuppressWarnings("unchecked") 273 private Coercion findOrCreateCoercion(Class sourceType, Class targetType) 274 { 275 if (sourceType == Void.class) 276 { 277 return searchForNullCoercion(targetType); 278 } 279 280 // These are instance variables because this method may be called concurrently. 281 // On a true race, we may go to the work of seeking out and/or fabricating 282 // a tuple twice, but it's more likely that different threads are looking 283 // for different source/target coercions. 284 285 Set<CoercionTuple> consideredTuples = CollectionFactory.newSet(); 286 LinkedList<CoercionTuple> queue = CollectionFactory.newLinkedList(); 287 288 seedQueue(sourceType, targetType, consideredTuples, queue); 289 290 while (!queue.isEmpty()) 291 { 292 CoercionTuple tuple = queue.removeFirst(); 293 294 // If the tuple results in a value type that is assignable to the desired target type, 295 // we're done! Later, we may add a concept of "cost" (i.e. number of steps) or 296 // "quality" (how close is the tuple target type to the desired target type). Cost 297 // is currently implicit, as compound tuples are stored deeper in the queue, 298 // so simpler coercions will be located earlier. 299 300 Class tupleTargetType = tuple.getTargetType(); 301 302 if (targetType.isAssignableFrom(tupleTargetType)) 303 { 304 return tuple.getCoercion(); 305 } 306 307 // So .. this tuple doesn't get us directly to the target type. 308 // However, it *may* get us part of the way. Each of these 309 // represents a coercion from the source type to an intermediate type. 310 // Now we're going to look for conversions from the intermediate type 311 // to some other type. 312 313 queueIntermediates(sourceType, targetType, tuple, consideredTuples, queue); 314 } 315 316 // Not found anywhere. Identify the source and target type and a (sorted) list of 317 // all the known coercions. 318 319 throw new UnknownValueException(String.format("Could not find a coercion from type %s to type %s.", 320 sourceType.getName(), targetType.getName()), buildCoercionCatalog()); 321 } 322 323 /** 324 * Coercion from null is special; we match based on the target type and its not a spanning 325 * search. In many cases, we 326 * return a pass-thru that leaves the value as null. 327 * 328 * @param targetType 329 * desired type 330 * @return the coercion 331 */ 332 private Coercion searchForNullCoercion(Class targetType) 333 { 334 List<CoercionTuple> tuples = getTuples(Void.class, targetType); 335 336 for (CoercionTuple tuple : tuples) 337 { 338 Class tupleTargetType = tuple.getTargetType(); 339 340 if (targetType.equals(tupleTargetType)) 341 return tuple.getCoercion(); 342 } 343 344 // Typical case: no match, this coercion passes the null through 345 // as null. 346 347 return COERCION_NULL_TO_OBJECT; 348 } 349 350 /** 351 * Builds a string listing all the coercions configured for the type coercer, sorted 352 * alphabetically. 353 */ 354 @SuppressWarnings("unchecked") 355 private AvailableValues buildCoercionCatalog() 356 { 357 List<CoercionTuple> masterList = CollectionFactory.newList(); 358 359 for (List<CoercionTuple> list : sourceTypeToTuple.values()) 360 { 361 masterList.addAll(list); 362 } 363 364 return new AvailableValues("Configured coercions", masterList); 365 } 366 367 /** 368 * Seeds the pool with the initial set of coercions for the given type. 369 */ 370 private void seedQueue(Class sourceType, Class targetType, Set<CoercionTuple> consideredTuples, 371 LinkedList<CoercionTuple> queue) 372 { 373 // Work from the source type up looking for tuples 374 375 for (Class c : new InheritanceSearch(sourceType)) 376 { 377 List<CoercionTuple> tuples = getTuples(c, targetType); 378 379 if (tuples == null) 380 { 381 continue; 382 } 383 384 for (CoercionTuple tuple : tuples) 385 { 386 queue.addLast(tuple); 387 consideredTuples.add(tuple); 388 } 389 390 // Don't pull in Object -> type coercions when doing 391 // a search from null. 392 393 if (sourceType == Void.class) 394 { 395 return; 396 } 397 } 398 } 399 400 /** 401 * Creates and adds to the pool a new set of coercions based on an intermediate tuple. Adds 402 * compound coercion tuples 403 * to the end of the queue. 404 * 405 * @param sourceType 406 * the source type of the coercion 407 * @param targetType 408 * TODO 409 * @param intermediateTuple 410 * a tuple that converts from the source type to some intermediate type (that is not 411 * assignable to the target type) 412 * @param consideredTuples 413 * set of tuples that have already been added to the pool (directly, or as a compound 414 * coercion) 415 * @param queue 416 * the work queue of tuples 417 */ 418 @SuppressWarnings("unchecked") 419 private void queueIntermediates(Class sourceType, Class targetType, CoercionTuple intermediateTuple, 420 Set<CoercionTuple> consideredTuples, LinkedList<CoercionTuple> queue) 421 { 422 Class intermediateType = intermediateTuple.getTargetType(); 423 424 for (Class c : new InheritanceSearch(intermediateType)) 425 { 426 for (CoercionTuple tuple : getTuples(c, targetType)) 427 { 428 if (consideredTuples.contains(tuple)) 429 { 430 continue; 431 } 432 433 Class newIntermediateType = tuple.getTargetType(); 434 435 // If this tuple is for coercing from an intermediate type back towards our 436 // initial source type, then ignore it. This should only be an optimization, 437 // as branches that loop back towards the source type will 438 // eventually be considered and discarded. 439 440 if (sourceType.isAssignableFrom(newIntermediateType)) 441 { 442 continue; 443 } 444 445 // The intermediateTuple coercer gets from S --> I1 (an intermediate type). 446 // The current tuple's coercer gets us from I2 --> X. where I2 is assignable 447 // from I1 (i.e., I2 is a superclass/superinterface of I1) and X is a new 448 // intermediate type, hopefully closer to our eventual target type. 449 450 Coercion compoundCoercer = new CompoundCoercion(intermediateTuple.getCoercion(), tuple.getCoercion()); 451 452 CoercionTuple compoundTuple = new CoercionTuple(sourceType, newIntermediateType, compoundCoercer, false); 453 454 // So, every tuple that is added to the queue can take as input the sourceType. 455 // The target type may be another intermediate type, or may be something 456 // assignable to the target type, which will bring the search to a successful 457 // conclusion. 458 459 queue.addLast(compoundTuple); 460 consideredTuples.add(tuple); 461 } 462 } 463 } 464 465 /** 466 * Returns a non-null list of the tuples from the source type. 467 * 468 * @param sourceType 469 * used to locate tuples 470 * @param targetType 471 * used to add synthetic tuples 472 * @return non-null list of tuples 473 */ 474 private List<CoercionTuple> getTuples(Class sourceType, Class targetType) 475 { 476 List<CoercionTuple> tuples = sourceTypeToTuple.get(sourceType); 477 478 if (tuples == null) 479 { 480 tuples = Collections.emptyList(); 481 } 482 483 // So, when we see String and an Enum type, we add an additional synthetic tuple to the end 484 // of the real list. This is the easiest way to accomplish this is a thread-safe and class-reloading 485 // safe way (i.e., what if the Enum is defined by a class loader that gets discarded? Don't want to cause 486 // memory leaks by retaining an instance). In any case, there are edge cases where we may create 487 // the tuple unnecessarily (such as when an explicit string-to-enum coercion is part of the TypeCoercer 488 // configuration), but on the whole, this is cheap and works. 489 490 if (sourceType == String.class && Enum.class.isAssignableFrom(targetType)) 491 { 492 tuples = extend(tuples, new CoercionTuple(sourceType, targetType, new StringToEnumCoercion(targetType))); 493 } 494 495 return tuples; 496 } 497 498 private static <T> List<T> extend(List<T> list, T extraValue) 499 { 500 return F.flow(list).append(extraValue).toList(); 501 } 502}