CollectInjectionProvidersFromStepsInstance.java

  1. package org.jbehave.core.steps.needle.configuration;

  2. import java.lang.reflect.Field;
  3. import java.util.Arrays;
  4. import java.util.LinkedHashSet;
  5. import java.util.Set;

  6. import org.jbehave.core.annotations.needle.NeedleInjectionProvider;
  7. import org.needle4j.injection.InjectionProvider;
  8. import org.needle4j.injection.InjectionProviderInstancesSupplier;
  9. import org.needle4j.reflection.ReflectionUtil;

  10. /**
  11.  * Collects {@link InjectionProvider} instances.
  12.  *
  13.  * @author Jan Galinski, Holisticon AG (jan.galinski@holisticon.de)
  14.  * @author Simon Zambrovski, Holisticon AG (simon.zambrovski@holisticon.de)
  15.  */
  16. public enum CollectInjectionProvidersFromStepsInstance {
  17.     /**
  18.      * stateless Singleton
  19.      */
  20.     INSTANCE;

  21.     /**
  22.      * Collect providers direct in the step definition.
  23.      *
  24.      * @param instance
  25.      *            step definition instance
  26.      * @return collected injection providers.
  27.      */
  28.     public final <T> InjectionProvider<?>[] apply(final T instance) {
  29.         final Set<InjectionProvider<?>> providers = new LinkedHashSet<>();
  30.         for (final Field field : ReflectionUtil.getAllFieldsWithAnnotation(instance, NeedleInjectionProvider.class)) {
  31.             field.setAccessible(true);
  32.             try {
  33.                 final Object value = field.get(instance);
  34.                 if (value instanceof InjectionProvider<?>[]) {
  35.                     providers.addAll(Arrays.asList((InjectionProvider<?>[]) value));
  36.                 } else if (value instanceof InjectionProvider) {
  37.                     providers.add((InjectionProvider<?>) value);
  38.                 } else if (value instanceof InjectionProviderInstancesSupplier) {
  39.                     providers.addAll(((InjectionProviderInstancesSupplier) value).get());
  40.                 } else {
  41.                     throw new IllegalStateException("Fields annotated with NeedleInjectionProviders must be of type "
  42.                             + "InjectionProviderInstancesSupplier, InjectionProvider " + "or InjectionProvider[]");
  43.                 }
  44.             } catch (final Exception e) {
  45.                 throw new IllegalStateException(e);
  46.             }
  47.         }

  48.         return providers.toArray(new InjectionProvider<?>[providers.size()]);
  49.     }

  50. }