Java 类com.google.inject.matcher.AbstractMatcher 实例源码

项目:Equella    文件:SecurityModule.java   
@Override
protected void configure()
{
    PluginService pluginService = AbstractPluginService.get();
    MethodSecurityInteceptor interceptor = pluginService.getBeanLocator(
        pluginService.getPluginIdForObject(getClass())).getBeanForType(MethodSecurityInteceptor.class);
    final SecurityAttributeSource source = interceptor.getAttributeSource();
    final TargetClassMatcher targetClassMatcher = new TargetClassMatcher();
    bindInterceptor(targetClassMatcher, new AbstractMatcher<Method>()
    {
        @Override
        public boolean matches(Method t)
        {
            if( !t.isSynthetic() )
            {
                return source.getAttribute(t, targetClassMatcher.getTargetClass()) != null;
            }
            return false;
        }
    }, interceptor);
}
项目:Mastering-Mesos    文件:GuiceUtils.java   
/**
 * Creates a matcher that will match methods of an interface, optionally excluding inherited
 * methods.
 *
 * @param matchInterface The interface to match.
 * @param declaredMethodsOnly if {@code true} only methods directly declared in the interface
 *                            will be matched, otherwise all methods on the interface are matched.
 * @return A new matcher instance.
 */
public static Matcher<Method> interfaceMatcher(
    Class<?> matchInterface,
    boolean declaredMethodsOnly) {

  Method[] methods =
      declaredMethodsOnly ? matchInterface.getDeclaredMethods() : matchInterface.getMethods();
  final Set<Pair<String, Class<?>[]>> interfaceMethods =
      ImmutableSet.copyOf(Iterables.transform(ImmutableList.copyOf(methods), CANONICALIZE));
  final LoadingCache<Method, Pair<String, Class<?>[]>> cache = CacheBuilder.newBuilder()
      .build(CacheLoader.from(CANONICALIZE));

  return new AbstractMatcher<Method>() {
    @Override
    public boolean matches(Method method) {
      return interfaceMethods.contains(cache.getUnchecked(method));
    }
  };
}
项目:qbit-extensions    文件:AuthorizedGuiceModule.java   
@Override
protected void configure() {
    bindInterceptor(Matchers.any(), new AbstractMatcher<Method>() {
        @Override
        public boolean matches(Method method) {
            return getAuthAnnotations(method.getAnnotations()).isPresent();
        }


    }, new MethodInterceptor() {
        @Override
        public Object invoke(MethodInvocation ctx) throws Throwable {
            Optional<Auth> methodAnnotation = getAuthAnnotations(ctx.getMethod().getAnnotations());

            boolean allowAnon = methodAnnotation.map(Auth::pass).orElse(true);

            if (!allowAnon) {
                throw new Exception("Access denied");
            }

            return ctx.proceed();
        }
    });
}
项目:salta    文件:ProvisionListenerTest.java   
public void testExceptionInFieldProvision() throws Exception {
    final CountAndCaptureExceptionListener listener = new CountAndCaptureExceptionListener();
    Injector injector = Guice.createInjector(new AbstractModule() {
        @Override
        protected void configure() {
            bindListener(new AbstractMatcher<TypeToken<?>>() {
                @Override
                public boolean matches(TypeToken<?> binding) {
                    return binding.getRawType()
                            .equals(DependsOnFooBombInField.class);
                }
            }, listener);
        }
    });
    assertEquals(0, listener.beforeProvision);
    try {
        injector.getInstance(DependsOnFooBombInField.class);
        fail();
    } catch (SaltaException e) {
        if (!e.getMessage().contains("Retry, Abort, Fail"))
            throw e;
    }
    assertEquals(1, listener.beforeProvision);
    assertEquals("Retry, Abort, Fail", listener.capture.get().getMessage());
    assertEquals(0, listener.afterProvision);
}
项目:salta    文件:ProvisionListenerTest.java   
public void testExceptionInCxtorProvision() throws Exception {
    final CountAndCaptureExceptionListener listener = new CountAndCaptureExceptionListener();
    Injector injector = Guice.createInjector(new AbstractModule() {
        @Override
        protected void configure() {
            bindListener(new AbstractMatcher<TypeToken<?>>() {
                @Override
                public boolean matches(TypeToken<?> type) {
                    return type.getRawType()
                            .equals(DependsOnFooBombInCxtor.class);
                }
            }, listener);
        }
    });
    assertEquals(0, listener.beforeProvision);
    try {
        injector.getInstance(DependsOnFooBombInCxtor.class);
        fail();
    } catch (SaltaException expected) {
        if (!expected.getMessage().contains("Retry, Abort, Fail"))
            throw expected;
    }
    assertEquals(1, listener.beforeProvision);
    assertEquals("Retry, Abort, Fail", listener.capture.get().getMessage());
    assertEquals(0, listener.afterProvision);
}
项目:salta    文件:ProvisionListenerTest.java   
public void testToProviderInstance() {
    final AtomicBoolean notified = new AtomicBoolean();
    Guice.createInjector(new AbstractModule() {
        @Override
        protected void configure() {
            bind(Object.class).toProvider(new Provider<Object>() {
                @Inject
                Foo foo;

                @Override
                public Object get() {
                    return null;
                }
            });
            bindListener(new AbstractMatcher<TypeToken<?>>() {

                @Override
                public boolean matches(TypeToken<?> t) {
                    return !Object.class.equals(t.getRawType())
                            && !Injector.class.equals(t.getRawType());
                }
            }, new SpecialChecker(Foo.class, notified));
        }
    }).getInstance(Object.class);
    assertTrue(notified.get());
}
项目:guice-persist-orient    文件:RepositoryModule.java   
/**
 * Configures repository annotations interceptor.
 */
protected void configureAop() {
    final RepositoryMethodInterceptor proxy = new RepositoryMethodInterceptor();
    requestInjection(proxy);
    // repository specific method annotations (query, function, delegate, etc.)
    bindInterceptor(Matchers.any(), new AbstractMatcher<Method>() {
        @Override
        public boolean matches(final Method method) {
            // this will throw error if two or more annotations specified (fail fast)
            try {
                return ExtUtils.findMethodAnnotation(method) != null;
            } catch (Exception ex) {
                throw new MethodDefinitionException(String.format("Error declaration on method %s",
                        RepositoryUtils.methodToString(method)), ex);
            }
        }
    }, proxy);
}
项目:guice    文件:TypeConverterBindingProcessor.java   
private static void convertToClasses(
    InjectorImpl injector, final Matcher<? super Class<?>> typeMatcher, TypeConverter converter) {
  internalConvertToTypes(
      injector,
      new AbstractMatcher<TypeLiteral<?>>() {
        @Override
        public boolean matches(TypeLiteral<?> typeLiteral) {
          Type type = typeLiteral.getType();
          if (!(type instanceof Class)) {
            return false;
          }
          Class<?> clazz = (Class<?>) type;
          return typeMatcher.matches(clazz);
        }

        @Override
        public String toString() {
          return typeMatcher.toString();
        }
      },
      converter);
}
项目:guice    文件:MethodInterceptionTest.java   
public void testInterceptingNonBridgeWorks() {
  Injector injector =
      Guice.createInjector(
          new AbstractModule() {
            @Override
            protected void configure() {
              bind(Interface.class).to(Impl.class);
              bindInterceptor(
                  Matchers.any(),
                  new AbstractMatcher<Method>() {
                    @Override
                    public boolean matches(Method t) {
                      return !t.isBridge() && t.getDeclaringClass() != Object.class;
                    }
                  },
                  new CountingInterceptor());
            }
          });
  Interface intf = injector.getInstance(Interface.class);
  assertEquals(0, count.get());
  intf.aMethod(null);
  assertEquals(1, count.get());
}
项目:guice    文件:ProvisionListenerTest.java   
public void testSingletonMatcher() {
  final Counter counter = new Counter();
  Injector injector =
      Guice.createInjector(
          new AbstractModule() {
            @Override
            protected void configure() {
              bindListener(
                  new AbstractMatcher<Binding<?>>() {
                    @Override
                    public boolean matches(Binding<?> t) {
                      return Scopes.isSingleton(t);
                    }
                  },
                  counter);
            }
          });
  assertEquals(0, counter.count);
  // no increment for getting Many.
  injector.getInstance(Many.class);
  assertEquals(0, counter.count);
  // but an increment for getting Sole, since it's a singleton.
  injector.getInstance(Sole.class);
  assertEquals(1, counter.count);
}
项目:guice-old    文件:TypeConverterBindingProcessor.java   
private static void convertToClasses(InjectorImpl injector,
    final Matcher<? super Class<?>> typeMatcher, TypeConverter converter) {
  internalConvertToTypes(injector, new AbstractMatcher<TypeLiteral<?>>() {
    public boolean matches(TypeLiteral<?> typeLiteral) {
      Type type = typeLiteral.getType();
      if (!(type instanceof Class)) {
        return false;
      }
      Class<?> clazz = (Class<?>) type;
      return typeMatcher.matches(clazz);
    }

    @Override public String toString() {
      return typeMatcher.toString();
    }
  }, converter);
}
项目:guice-old    文件:MethodInterceptionTest.java   
public void testInterceptingNonBridgeWorks() {
  Injector injector = Guice.createInjector(new AbstractModule() {
    @Override
    protected void configure() {
      bind(Interface.class).to(Impl.class);
      bindInterceptor(Matchers.any(), new AbstractMatcher<Method>() {
        public boolean matches(Method t) {
          return !t.isBridge() && t.getDeclaringClass() != Object.class;
        }
      }, new CountingInterceptor());
    }
  });
  Interface intf = injector.getInstance(Interface.class);
  assertEquals(0, count.get());
  intf.aMethod(null);
  assertEquals(1, count.get());
}
项目:guice-old    文件:ProvisionListenerTest.java   
public void testSingletonMatcher() {
  final Counter counter = new Counter();
  Injector injector = Guice.createInjector(new AbstractModule() {
    @Override
    protected void configure() {
      bindListener(new AbstractMatcher<Binding<?>>() {
        @Override
        public boolean matches(Binding<?> t) {
          return Scopes.isSingleton(t);
        }
      }, counter);
    }
  });
  assertEquals(0, counter.count);
  // no increment for getting Many.
  injector.getInstance(Many.class);
  assertEquals(0, counter.count);
  // but an increment for getting Sole, since it's a singleton.
  injector.getInstance(Sole.class);
  assertEquals(1, counter.count);
}
项目:google-guice    文件:TypeConverterBindingProcessor.java   
private void convertToClasses(final Matcher<? super Class<?>> typeMatcher,
    TypeConverter converter) {
  internalConvertToTypes(new AbstractMatcher<TypeLiteral<?>>() {
    public boolean matches(TypeLiteral<?> typeLiteral) {
      Type type = typeLiteral.getType();
      if (!(type instanceof Class)) {
        return false;
      }
      Class<?> clazz = (Class<?>) type;
      return typeMatcher.matches(clazz);
    }

    @Override public String toString() {
      return typeMatcher.toString();
    }
  }, converter);
}
项目:google-guice    文件:MethodInterceptionTest.java   
public void testInterceptingNonBridgeWorks() {
  Injector injector = Guice.createInjector(new AbstractModule() {
    @Override
    protected void configure() {
      bind(Interface.class).to(Impl.class);
      bindInterceptor(Matchers.any(), new AbstractMatcher<Method>() {
        public boolean matches(Method t) {
          return !t.isBridge() && t.getDeclaringClass() != Object.class;
        }
      }, new CountingInterceptor());
    }
  });
  Interface intf = injector.getInstance(Interface.class);
  assertEquals(0, count.get());
  intf.aMethod(null);
  assertEquals(1, count.get());
}
项目:google-guice    文件:ProvisionListenerTest.java   
public void testSingletonMatcher() {
  final Counter counter = new Counter();
  Injector injector = Guice.createInjector(new AbstractModule() {
    @Override
    protected void configure() {
      bindListener(new AbstractMatcher<Binding<?>>() {
        @Override
        public boolean matches(Binding<?> t) {
          return Scopes.isSingleton(t);
        }
      }, counter);
    }
  });
  assertEquals(0, counter.count);
  // no increment for getting Many.
  injector.getInstance(Many.class);
  assertEquals(0, counter.count);
  // but an increment for getting Sole, since it's a singleton.
  injector.getInstance(Sole.class);
  assertEquals(1, counter.count);
}
项目:act-platform    文件:AbstractAspect.java   
/**
 * Create a Matcher which matches against a service method.
 *
 * @return Matcher matching a service method
 */
Matcher<Method> matchServiceMethod() {
  return new AbstractMatcher<Method>() {
    @Override
    public boolean matches(Method method) {
      return isServiceMethod(method);
    }
  };
}
项目:ProjectAres    文件:FunctionalMatcher.java   
@Override
default Matcher<T> and(com.google.inject.matcher.Matcher<? super T> other) {
    return new AbstractMatcher<T>() {
        @Override public boolean matches(T t) {
            return FunctionalMatcher.this.matches(t) && other.matches(t);
        }
    };
}
项目:ProjectAres    文件:FunctionalMatcher.java   
@Override
default Matcher<T> or(com.google.inject.matcher.Matcher<? super T> other) {
    return new AbstractMatcher<T>() {
        @Override public boolean matches(T t) {
            return FunctionalMatcher.this.matches(t) || other.matches(t);
        }
    };
}
项目:salta    文件:ProvisionListenerTest.java   
private static Matcher<Binding<?>> keyMatcher(final Class<?> clazz) {
    return new AbstractMatcher<Binding<?>>() {
        @Override
        public boolean matches(Binding<?> t) {
            return t.getKey().equals(Key.get(clazz));
        }
    };
}
项目:fathom    文件:AopModule.java   
protected final void bindShiroInterceptor(final AnnotationMethodInterceptor methodInterceptor) {
    bindInterceptor(Matchers.any(), new AbstractMatcher<Method>() {
        public boolean matches(Method method) {
            Class<? extends Annotation> annotation = methodInterceptor.getHandler().getAnnotationClass();
            return method.getAnnotation(annotation) != null
                    || method.getDeclaringClass().getAnnotation(annotation) != null;
        }
    }, new AopAllianceMethodInterceptorAdapter(methodInterceptor));
}
项目:datakernel    文件:WorkerPoolModule.java   
@Override
protected void configure() {
    workerPoolScope = new WorkerPoolScope();

    Provider<Injector> injectorProvider = getProvider(Injector.class);
    bindListener(new AbstractMatcher<Binding<?>>() {
        @Override
        public boolean matches(Binding<?> binding) {
            return binding.getKey().getTypeLiteral().getRawType() == WorkerPool.class;
        }
    }, new ProvisionListener() {
        @Override
        public <T> void onProvision(ProvisionInvocation<T> provision) {
            WorkerPool workerPool = (WorkerPool) provision.provision();
            workerPool.injector = injectorProvider.get();
            workerPool.poolScope = workerPoolScope;
        }
    });

    bindScope(Worker.class, workerPoolScope);
    bind(Integer.class).annotatedWith(WorkerId.class).toProvider(new Provider<Integer>() {
        @Override
        public Integer get() {
            return workerPoolScope.currentWorkerId;
        }
    });
}
项目:pbox    文件:ReflectionUtil.java   
public static Matcher<? super Class<?>> newClassOrSuperclassAnnotatedWithMatcher(
        final Class<? extends Annotation> annotationClass) {
    return new AbstractMatcher<Class<?>>() {
        @Override
        public boolean matches(Class<?> clazz) {
            return isClassOrSuperclassAnnotatedWith(clazz, annotationClass);
        }
    };
}
项目:pbox    文件:ReflectionUtil.java   
public static Matcher<? super Method> newComponentActionMethodMatcher() {
    return new AbstractMatcher<Method>() {
        @Override
        public boolean matches(Method method) {
            return "action".equals(method.getName())
                    || "validate".equals(method.getName())
                    || "invalid".equals(method.getName())
                    || method.isAnnotationPresent(Action.class)
                    || method.isAnnotationPresent(Validate.class)
                    || method.isAnnotationPresent(Invalid.class);
        }
    };
}
项目:guice-persist-orient    文件:OrientModule.java   
@Override
protected void bindInterceptor(final Matcher<? super Class<?>> classMatcher,
                               final Matcher<? super Method> methodMatcher,
                               final MethodInterceptor... interceptors) {
    // hack to correctly bind @Transactional annotation for java8:
    // aop tries to intercept synthetic methods which cause a lot of warnings
    // (and generally not correct)
    super.bindInterceptor(classMatcher, new AbstractMatcher<Method>() {
        @Override
        public boolean matches(final Method method) {
            return !method.isSynthetic() && !method.isBridge() && methodMatcher.matches(method);
        }
    }, interceptors);
}
项目:guice    文件:OSGiTestActivator.java   
@Override
protected void configure() {
  bindInterceptor(
      new AbstractMatcher<Class<?>>() {
        @Override
        public boolean matches(Class<?> clazz) {
          try {

            // the class and constructor must be visible
            int clazzModifiers = clazz.getModifiers();
            int ctorModifiers = clazz.getConstructor().getModifiers();
            return (clazzModifiers & (Modifier.PUBLIC | Modifier.PROTECTED)) != 0
                && (ctorModifiers & (Modifier.PUBLIC | Modifier.PROTECTED)) != 0;

          } catch (NoSuchMethodException e) {
            return false;
          }
        }
      },
      new AbstractMatcher<Method>() {
        @Override
        public boolean matches(Method method) {

          // the intercepted method must also be visible
          int methodModifiers = method.getModifiers();
          return (methodModifiers & (Modifier.PUBLIC | Modifier.PROTECTED)) != 0;
        }
      },
      new org.aopalliance.intercept.MethodInterceptor() {
        @Override
        public Object invoke(org.aopalliance.intercept.MethodInvocation mi) throws Throwable {

          return mi.proceed();
        }
      });
}
项目:guice    文件:ProvisionListenerTest.java   
private static Matcher<Binding<?>> keyMatcher(final Class<?> clazz) {
  return new AbstractMatcher<Binding<?>>() {
    @Override
    public boolean matches(Binding<?> t) {
      return t.getKey().equals(Key.get(clazz));
    }
  };
}
项目:ddp-client-java    文件:SampleApplicationModule.java   
@Override
protected void configure() {
    bind(SampleApplication.class);

    bind(MessageConverter.class).to(JsonMessageConverter.class).in(Singleton.class);
    bind(ObjectConverter.class).to(JsonObjectConverter.class).in(Singleton.class);
    bind(SubscriptionAdapter.class).to(MapSubscriptionAdapter.class).in(Singleton.class);
    bind(DDPMessageEndpoint.class).to(DDPMessageEndpointImpl.class).in(Singleton.class);
    bind(SubscriptionEventDispatcher.class).asEagerSingleton();
    bind(MeteorCollectionRepository.class).to(MeteorCollectionRepositoryImpl.class).in(Singleton.class);
    bind(RPCClient.class).to(RPCClientImpl.class).in(Singleton.class);
    bind(EventBus.class).in(Singleton.class);

    bindListener(
            new AbstractMatcher<TypeLiteral<?>>() {
                @Override
                public boolean matches(TypeLiteral<?> typeLiteral) {
                    return typeLiteral.getRawType().isAnnotationPresent(Presents.class);
                }
            },
            new TypeListener() {
                @Override
                public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) {
                    final Presents presents = type.getRawType().getAnnotation(Presents.class);
                    encounter.register((InjectionListener<I>) injectee -> {
                        final FXMLLoader loader = new FXMLLoader(injectee.getClass().getResource(presents.value()));
                        loader.setController(injectee);
                        try {
                            loader.load();
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    });
                }
            }
    );
}
项目:guice-old    文件:OSGiTestActivator.java   
@Override protected void configure() {
  bindInterceptor(new AbstractMatcher<Class<?>>() {
    public boolean matches(Class<?> clazz) {
      try {

        // the class and constructor must be visible
        int clazzModifiers = clazz.getModifiers();
        int ctorModifiers = clazz.getConstructor().getModifiers();
        return (clazzModifiers & (Modifier.PUBLIC | Modifier.PROTECTED)) != 0
            && (ctorModifiers & (Modifier.PUBLIC | Modifier.PROTECTED)) != 0;

      } catch (NoSuchMethodException e) {
        return false;
      }
    }
  }, new AbstractMatcher<Method>() {
    public boolean matches(Method method) {

      // the intercepted method must also be visible
      int methodModifiers = method.getModifiers();
      return (methodModifiers & (Modifier.PUBLIC | Modifier.PROTECTED)) != 0;

    }
  }, new org.aopalliance.intercept.MethodInterceptor() {
    public Object invoke(org.aopalliance.intercept.MethodInvocation mi)
        throws Throwable {

      return mi.proceed();
    }
  });
}
项目:guice-old    文件:ProvisionListenerTest.java   
private static Matcher<Binding<?>> keyMatcher(final Class<?> clazz) {
  return new AbstractMatcher<Binding<?>>() {
    @Override
    public boolean matches(Binding<?> t) {
      return t.getKey().equals(Key.get(clazz));
    }
  };
}
项目:google-guice    文件:OSGiTestActivator.java   
@Override protected void configure() {
  bindInterceptor(new AbstractMatcher<Class<?>>() {
    public boolean matches(Class<?> clazz) {
      try {

        // the class and constructor must be visible
        int clazzModifiers = clazz.getModifiers();
        int ctorModifiers = clazz.getConstructor().getModifiers();
        return (clazzModifiers & (Modifier.PUBLIC | Modifier.PROTECTED)) != 0
            && (ctorModifiers & (Modifier.PUBLIC | Modifier.PROTECTED)) != 0;

      } catch (NoSuchMethodException e) {
        return false;
      }
    }
  }, new AbstractMatcher<Method>() {
    public boolean matches(Method method) {

      // the intercepted method must also be visible
      int methodModifiers = method.getModifiers();
      return (methodModifiers & (Modifier.PUBLIC | Modifier.PROTECTED)) != 0;

    }
  }, new org.aopalliance.intercept.MethodInterceptor() {
    public Object invoke(org.aopalliance.intercept.MethodInvocation mi)
        throws Throwable {

      return mi.proceed();
    }
  });
}
项目:google-guice    文件:ProvisionListenerTest.java   
private static Matcher<Binding<?>> keyMatcher(final Class<?> clazz) {
  return new AbstractMatcher<Binding<?>>() {
    @Override
    public boolean matches(Binding<?> t) {
      return t.getKey().equals(Key.get(clazz));
    }
  };
}
项目:yar    文件:MatchersTest.java   
@Test
public void testGetTypeLiteralOfMatcherOfKeyOfString() throws Exception {
    TypeLiteral<String> stringTypeLiteral = getTargetTypeLiteral(new AbstractMatcher<Key<String>>() {
        @Override
        public boolean matches(Key<String> item) {
            return false;
        }
    });
    TypeLiteral<String> expectedTypeLiteral = new TypeLiteral<String>() {
    };

    assertThat(stringTypeLiteral, is(not(nullValue())));
    assertThat(stringTypeLiteral, is(expectedTypeLiteral));
}
项目:yar    文件:RegistryModuleBindTest.java   
@Test
public void testBindListenerSingleElement() {
    final org.javabits.yar.BlockingSupplierRegistry registry = newBlockingSupplierRegistry();
    Module module = newRegistryDeclarationModule(registry);
    final Object[] matches = new Object[]{0, null, null};

    Injector injector = createInjector(module, new RegistryModule() {
        @Override
        protected void configureRegistry() {
            bindRegistryListener(
                    new AbstractMatcher<Key<MyInterface>>() {
                        @Override
                        public boolean matches(Key<MyInterface> item) {
                            boolean equals = Key.get(MyInterface.class).equals(item);
                            matches[0] = (Integer) matches[0] + (equals ? 1 : 0);
                            return equals;
                        }
                    }, new MyInterfaceSingleElementWatcher(matches)
            );
        }
    });
    SupplierRegistration<MyInterface> myInterfaceRegistration = (SupplierRegistration<MyInterface>) putMyInterfaceSupplierToRegistry(registry);
    registry.remove(myInterfaceRegistration);

    assertThat(injector, is(not(nullValue())));
    assertThat((matches[0]), is(2));
    assertThat(matches[1], is(notNullValue()));
    assertThat((matches[2]), is(matches[1]));
}
项目:mynlp    文件:MyNlps.java   
private static Injector createInject() {

        Settings settings = Settings.build();

        Environment environment = new Environment(settings);


        ArrayList<Module> modules = Lists.newArrayList();

        modules.add(new AbstractModule() {
            @Override
            protected void configure() {

                bind(Settings.class).toInstance(settings);
                bind(Environment.class).toInstance(environment);
                bind(MynlpResourceFactory.class).toInstance(environment.getMynlpResourceFactory());

                //process initialize interface
                bindListener(new AbstractMatcher<TypeLiteral<?>>() {
                    @Override
                    public boolean matches(TypeLiteral<?> t) {
                        return InitInterface.class.isAssignableFrom(t.getRawType());
                    }
                }, new TypeListener() {
                    @SuppressWarnings({"unchecked", "rawtypes"})
                    @Override
                    public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) {
                        encounter.register((InjectionListener) injectee -> {
                            InitInterface initInterface = (InitInterface) injectee;
                            try {
                                initInterface.init();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        });
                    }
                });

            }
        });


        //加载模块,在配置文件中声明的
        modules.addAll(loadModules(environment));

        Injector injector = Guice.createInjector(modules);

        return injector;
    }
项目:guice    文件:ProvisionListenerTest.java   
public void testExceptionInFieldProvision() throws Exception {
  final CountAndCaptureExceptionListener listener = new CountAndCaptureExceptionListener();
  Injector injector =
      Guice.createInjector(
          new AbstractModule() {
            @Override
            protected void configure() {
              bindListener(
                  new AbstractMatcher<Binding<?>>() {
                    @Override
                    public boolean matches(Binding<?> binding) {
                      return binding.getKey().getRawType().equals(DependsOnFooBombInField.class);
                    }
                  },
                  listener);
            }
          });
  assertEquals(0, listener.beforeProvision);
  String expectedMsg = null;
  try {
    injector.getInstance(DependsOnFooBombInField.class);
    fail();
  } catch (ProvisionException expected) {
    assertEquals(1, expected.getErrorMessages().size());
    expectedMsg = Iterables.getOnlyElement(expected.getErrorMessages()).getMessage();
    assertContains(
        expected.getMessage(),
        "1) Error injecting constructor, java.lang.RuntimeException: Retry, Abort, Fail",
        " at " + FooBomb.class.getName(),
        " while locating " + FooBomb.class.getName(),
        " while locating " + DependsOnFooBombInField.class.getName());
    assertContains(
        listener.capture.get().getMessage(),
        "1) Error injecting constructor, java.lang.RuntimeException: Retry, Abort, Fail",
        " at " + FooBomb.class.getName(),
        " while locating " + FooBomb.class.getName());
    // The message that is captures by the provision listener does not show what is depending on
    // the thing being listened to.
    assertThat(listener.capture.get().getMessage())
        .doesNotContain(" while locating " + DependsOnFooBombInField.class.getName());
  }
  assertEquals(1, listener.beforeProvision);
  assertEquals(
      expectedMsg,
      Iterables.getOnlyElement(((ProvisionException) listener.capture.get()).getErrorMessages())
          .getMessage());
  assertEquals(0, listener.afterProvision);
}
项目:guice    文件:ProvisionListenerTest.java   
public void testExceptionInCxtorProvision() throws Exception {
  final CountAndCaptureExceptionListener listener = new CountAndCaptureExceptionListener();
  Injector injector =
      Guice.createInjector(
          new AbstractModule() {
            @Override
            protected void configure() {
              bindListener(
                  new AbstractMatcher<Binding<?>>() {
                    @Override
                    public boolean matches(Binding<?> binding) {
                      return binding.getKey().getRawType().equals(DependsOnFooBombInCxtor.class);
                    }
                  },
                  listener);
            }
          });
  assertEquals(0, listener.beforeProvision);
  String expectedMsg = null;
  try {
    injector.getInstance(DependsOnFooBombInCxtor.class);
    fail();
  } catch (ProvisionException expected) {
    assertEquals(1, expected.getErrorMessages().size());
    expectedMsg = Iterables.getOnlyElement(expected.getErrorMessages()).getMessage();
    assertContains(
        expected.getMessage(),
        "1) Error injecting constructor, java.lang.RuntimeException: Retry, Abort, Fail",
        " at " + FooBomb.class.getName(),
        " while locating " + FooBomb.class.getName(),
        " while locating " + DependsOnFooBombInCxtor.class.getName());
    assertContains(
        listener.capture.get().getMessage(),
        "1) Error injecting constructor, java.lang.RuntimeException: Retry, Abort, Fail",
        " at " + FooBomb.class.getName(),
        " while locating " + FooBomb.class.getName());
    // The message that is captures by the provision listener does not show what is depending on
    // the thing being listened to.
    assertThat(listener.capture.get().getMessage())
        .doesNotContain(" while locating " + DependsOnFooBombInField.class.getName());
  }
  assertEquals(1, listener.beforeProvision);
  assertEquals(
      expectedMsg,
      Iterables.getOnlyElement(((ProvisionException) listener.capture.get()).getErrorMessages())
          .getMessage());
  assertEquals(0, listener.afterProvision);
}
项目:griffon2    文件:GuiceInjectorFactory.java   
private GuiceInjector createModules(final @Nonnull GriffonApplication application, @Nonnull final InjectorProvider injectorProvider, @Nonnull Iterable<Binding<?>> bindings) {
    final InjectionListener<GriffonArtifact> injectionListener = new InjectionListener<GriffonArtifact>() {
        @Override
        public void afterInjection(GriffonArtifact injectee) {
            application.getEventRouter().publishEvent(
                ApplicationEvent.NEW_INSTANCE.getName(),
                asList(injectee.getClass(), injectee)
            );
        }
    };


    Module injectorModule = new AbstractModule() {
        @Override
        protected void configure() {
            bind(Injector.class)
                .toProvider(guicify(injectorProvider))
                .in(Singleton.class);

            bindListener(new AbstractMatcher<TypeLiteral<?>>() {
                             public boolean matches(TypeLiteral<?> typeLiteral) {
                                 return GriffonArtifact.class.isAssignableFrom(typeLiteral.getRawType());
                             }
                         }, new TypeListener() {
                             @SuppressWarnings("unchecked")
                             @Override
                             public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) {
                                 if (GriffonArtifact.class.isAssignableFrom(type.getRawType())) {
                                     TypeEncounter<GriffonArtifact> artifactEncounter = (TypeEncounter<GriffonArtifact>) encounter;
                                     artifactEncounter.register(injectionListener);
                                 }
                             }
                         }
            );
        }
    };

    Collection<Module> modules = new ArrayList<>();
    modules.add(injectorModule);
    modules.add(moduleFromBindings(bindings));

    ServiceLoader<Module> moduleLoader = ServiceLoader.load(Module.class, getClass().getClassLoader());
    for (Module module : moduleLoader) {
        modules.add(module);
    }

    com.google.inject.Injector injector = Guice.createInjector(modules);
    return new GuiceInjector(injector);
}
项目:t4f-data    文件:PersistenceMatchers.java   
/**
 * Matches on all {@code @}{@link com.wideplay.warp.persist.dao.Finder} annotations
 * that have the specified unit.
 * <pre>
 * {@code finderWithUnit(Sales.class) => @Finder(unit=Sales.class)}
 * </pre>
 * @param annotation the unit annotation
 * @return a matcher that matches on {@code @Finder(unit=annotation)}
 */
static Matcher<AnnotatedElement> finderWithUnit(final Class<?> annotation) {
    return new AbstractMatcher<AnnotatedElement>() {
        public boolean matches(AnnotatedElement annotatedElement) {
            return annotatedWith(Finder.class).matches(annotatedElement) &&
                   annotatedElement.getAnnotation(Finder.class).unit() == annotation;
        }
    };
}
项目:t4f-data    文件:PersistenceMatchers.java   
/**
 * Matches on all {@code @}{@link com.wideplay.warp.persist.Transactional} annotations
 * that have the specified unit.
 * <pre>
 * {@code transactionalWithUnit(Sales.class) => @Transactional(unit=Sales.class)}
 * </pre>
 * @param annotation the unit annotation
 * @return a matcher that matches on {@code @Transactional(unit=annotation)}
 */
public static Matcher<AnnotatedElement> transactionalWithUnit(final Class<?> annotation) {
    return new AbstractMatcher<AnnotatedElement>() {
        public boolean matches(AnnotatedElement annotatedElement) {
            return annotatedWith(Transactional.class).matches(annotatedElement) &&
                   annotatedElement.getAnnotation(Transactional.class).unit() == annotation;
        }
    };
}