Ejemplo n.º 1
0
  @Override
  public <T> T convertTo(Class<T> type, Exchange exchange, Object value)
      throws TypeConversionException {
    // find the map id, so we can provide that when trying to map from source to destination
    String mapId = null;
    if (value != null) {
      Class<?> sourceType = value.getClass();
      Class<?> destType = type;
      ClassMappingMetadata metadata =
          mapper.getMappingMetadata().getClassMapping(sourceType, destType);
      if (metadata != null) {
        mapId = metadata.getMapId();
      }
    }

    // if the exchange is null, we have no chance to ensure that the TCCL is the one from the
    // CamelContext
    if (exchange == null) {
      return mapper.map(value, type, mapId);
    }

    T answer = null;

    ClassLoader prev = Thread.currentThread().getContextClassLoader();
    ClassLoader contextCl = exchange.getContext().getApplicationContextClassLoader();
    if (contextCl != null) {
      // otherwise, we ensure that the TCCL is the correct one
      LOG.debug("Switching TCCL to: {}.", contextCl);
      try {
        Thread.currentThread().setContextClassLoader(contextCl);
        answer = mapper.map(value, type, mapId);
      } finally {
        LOG.debug("Restored TCCL to: {}.", prev);
        Thread.currentThread().setContextClassLoader(prev);
      }
    } else {
      // just try with the current TCCL as-is
      answer = mapper.map(value, type, mapId);
    }

    return answer;
  }