All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.stickycode.configured.guice3.strategy.GuiceStrategyFinder Maven / Gradle / Ivy

package net.stickycode.configured.guice3.strategy;

import java.beans.Introspector;
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.Set;

import javax.inject.Inject;

import net.stickycode.configured.ConfigurationKeyBuilder;
import net.stickycode.configured.strategy.StrategyFinder;
import net.stickycode.configured.strategy.StrategyNotFoundException;
import net.stickycode.stereotype.StickyComponent;

import com.google.inject.Binding;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
import com.google.inject.util.Types;

@StickyComponent
public class GuiceStrategyFinder
    implements StrategyFinder {

  @Inject
  Injector injector;
  
  @Inject
  ConfigurationKeyBuilder builder;

  @SuppressWarnings({ "rawtypes", "unchecked" })
  @Override
  public Object findWithName(Class contract, String name) throws StrategyNotFoundException {
    Binding b = injector.getBinding(Key.get(setOf(TypeLiteral.get(contract))));
    for (Object o : b.getProvider().get()) {
      if (name.equals(Introspector.decapitalize(o.getClass().getSimpleName())))
        return o;
    }
    
    throw new StrategyNotFoundException(contract, name, Collections.emptySet());
  }

  @SuppressWarnings("unchecked")
  // wrapping a T in a Set safely returns a Set
  static  TypeLiteral> setOf(TypeLiteral elementType) {
    Type type = Types.setOf(elementType.getType());
    return (TypeLiteral>) TypeLiteral.get(type);
  }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy