PageRenderTime 26ms CodeModel.GetById 21ms app.highlight 3ms RepoModel.GetById 1ms app.codeStats 0ms

/sitebricks-converter/src/main/java/com/google/sitebricks/conversion/MvelConversionHandlers.java

http://github.com/dhanji/sitebricks
Java | 69 lines | 51 code | 14 blank | 4 comment | 5 complexity | 65a23421f0661a9879768ed3d7eba686 MD5 | raw file
 1package com.google.sitebricks.conversion;
 2
 3import java.lang.reflect.ParameterizedType;
 4import java.lang.reflect.Type;
 5import java.util.Collection;
 6
 7import org.mvel2.ConversionHandler;
 8import org.mvel2.DataConversion;
 9
10import com.google.common.primitives.Primitives;
11import com.google.inject.Inject;
12import com.google.sitebricks.conversion.generics.Generics;
13
14/**
15 * @author John Patterson (jdpatterson@gmail.com)
16 */
17public class MvelConversionHandlers {
18
19  private TypeConverter delegate;
20  private ConverterRegistry registry;
21
22  @Inject
23  public void prepare(ConverterRegistry registry, TypeConverter delegate) {
24    this.registry = registry;
25    this.delegate = delegate;
26
27    Collection<Converter<?, ?>> converters = registry.getConvertersBySource().values();
28    for (Converter<?, ?> converter : converters) {
29      ParameterizedType converterType = (ParameterizedType) Generics.getExactSuperType(
30          converter.getClass(), Converter.class);
31
32      Type[] converterParameters = converterType.getActualTypeArguments();
33      registerMvelHandler(converterParameters[0]);
34      registerMvelHandler(converterParameters[1]);
35    }
36  }
37
38  private void registerMvelHandler(Type targetType) {
39    Class<?> targetClass = Generics.erase(targetType);
40    SitebricksConversionHandler targetHandler = new SitebricksConversionHandler(targetType);
41    DataConversion.addConversionHandler(targetClass, targetHandler);
42    if (Primitives.isWrapperType(targetClass)) {
43      DataConversion.addConversionHandler(Primitives.unwrap(targetClass), targetHandler);
44    }
45  }
46
47  private class SitebricksConversionHandler implements ConversionHandler {
48    private final Type targetType;
49
50    public SitebricksConversionHandler(Type targetType) {
51      this.targetType = targetType;
52    }
53
54    @Override
55    public Object convertFrom(Object in) {
56      return delegate.convert(in, targetType);
57    }
58
59    @SuppressWarnings("unchecked")
60    @Override
61    public boolean canConvertFrom(@SuppressWarnings("rawtypes") Class cls) {
62      if (cls == targetType)
63        return true;
64      
65      // check that there is a converter registered for this source type
66      return registry.converter(Primitives.wrap(cls), targetType) != null;
67    }
68  }
69}