com.google.inject.spi.Elements Java Examples

The following examples show how to use com.google.inject.spi.Elements. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WebMappingsRenderer.java    From dropwizard-guicey with MIT License 6 votes vote down vote up
private void renderGuiceWeb(final TreeNode filter) throws Exception {
    final List<String> servlets = new ArrayList<>();
    final List<String> filters = new ArrayList<>();

    for (Element element : Elements.getElements(Stage.TOOL, modules)) {
        if (!(element instanceof Binding)) {
            continue;
        }
        @SuppressWarnings("unchecked") final WebElementModel model =
                (WebElementModel) ((Binding) element).acceptTargetVisitor(VISITOR);
        if (model == null) {
            continue;
        }
        final String line = renderGuiceWebElement(model, element);
        if (model.getType().equals(WebElementType.FILTER)) {
            filters.add(line);
        } else {
            servlets.add(line);
        }
    }
    renderGucieWebElements(servlets, filters, filter);
}
 
Example #2
Source File: Binders.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
default void installIn(Scoping scoping, Module... modules) {
    final Scoper scoper = new Scoper(this, scoping);
    for(Element element : Elements.getElements(modules)) {
        if(element instanceof Binding) {
            ((Binding) element).acceptTargetVisitor(scoper);
        } else {
            element.applyTo(this);
        }
    }
}
 
Example #3
Source File: EndpointsModuleTest.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  module = new EndpointsModule() {
    @Override
    protected void configureServlets() {
      super.configureServlets();
      configureEndpoints(URL_PATTERN, INIT_PARAMETERS, true);
    }
  };
  Elements.getElements(module);
}
 
Example #4
Source File: GuiceRepository.java    From vespa with Apache License 2.0 5 votes vote down vote up
private Module createModule() {
    List<Element> allElements = new LinkedList<>();
    for (List<Element> moduleElements : modules.values()) {
        allElements.addAll(moduleElements);
    }
    ElementCollector collector = new ElementCollector();
    for (ListIterator<Element> it = allElements.listIterator(allElements.size()); it.hasPrevious(); ) {
        it.previous().acceptVisitor(collector);
    }
    return Elements.getModule(collector.elements);
}
 
Example #5
Source File: ModuleTester.java    From mail-importer with Apache License 2.0 5 votes vote down vote up
public void assertAllDependenciesDeclared() {
  List<Key> requiredKeys = new ArrayList<>();

  List<Element> elements = Elements.getElements(module);
  for (Element element : elements) {
    element.acceptVisitor(new DefaultElementVisitor<Void>() {
      @Override
      public <T> Void visit(ProviderLookup<T> providerLookup) {
        // Required keys are the only ones with null injection points.
        if (providerLookup.getDependency().getInjectionPoint() == null) {
          requiredKeys.add(providerLookup.getKey());
        }
        return null;
      }
    });
  }

  Injector injector = Guice.createInjector(module,
      new AbstractModule() {
        @Override
        @SuppressWarnings("unchecked")
        protected void configure() {
          binder().disableCircularProxies();
          binder().requireAtInjectOnConstructors();
          binder().requireExactBindingAnnotations();

          for (Key<?> key : requiredKeys) {
            bind((Key) key).toProvider(Providers.of(null));
          }
        }
      });

  injector.getAllBindings();
}
 
Example #6
Source File: GuiceAopMapRenderer.java    From dropwizard-guicey with MIT License 5 votes vote down vote up
@Override
public String renderReport(final GuiceAopConfig config) {
    final StringBuilder res = new StringBuilder();

    // AOP declarations
    final List<Element> declared = Elements.getElements(Stage.TOOL, modules).stream()
            .filter(it -> it instanceof InterceptorBinding)
            .collect(Collectors.toList());

    if (!config.isHideDeclarationsBlock()) {
        final List<ModuleDeclaration> declarationModules = GuiceModelParser.parse(injector, declared);
        res.append(Reporter.NEWLINE).append(Reporter.NEWLINE);
        renderDeclared(declarationModules, res);
    }

    if (!declared.isEmpty()) {
        // AOP appliance map
        final List<Binding> guiceManagedObjects = injector.getAllBindings().values().stream()
                .filter(it -> it instanceof ConstructorBinding)
                .collect(Collectors.toList());
        final List<AopDeclaration> tree = filter(GuiceModelParser.parse(injector, guiceManagedObjects), config);
        if (!tree.isEmpty()) {
            res.append(Reporter.NEWLINE).append(Reporter.NEWLINE);
            renderMap(tree, res);
        }
    }
    return res.toString();
}
 
Example #7
Source File: GuiceBindingsRenderer.java    From dropwizard-guicey with MIT License 5 votes vote down vote up
@Override
public String renderReport(final GuiceConfig config) {
    // analyze modules
    final List<ModuleDeclaration> moduleItems = filter(
            GuiceModelParser.parse(injector, Elements.getElements(Stage.TOOL, modules)), config);
    final Map<Key, BindingDeclaration> moduleBindings = GuiceModelUtils.index(moduleItems);

    // don't show extensions if no guice module analysis actually performed
    if (analysisEnabled) {
        markExtensions(moduleBindings);
    }

    // analyze overrides
    final List<ModuleDeclaration> overrideItems = filter(overridden.isEmpty()
            ? Collections.emptyList() : GuiceModelParser.parse(injector,
            Elements.getElements(Stage.TOOL, overridden)), config);
    final Map<Key, BindingDeclaration> overrideBindings = GuiceModelUtils.index(overrideItems);

    markOverrides(moduleBindings, overrideBindings);

    final StringBuilder res = new StringBuilder();
    res.append(Reporter.NEWLINE).append(Reporter.NEWLINE);

    // put all known bindings together for remaining reports
    renderModules(res, moduleItems, moduleBindings);
    renderOverrides(res, overrideItems, overrideBindings);
    moduleBindings.putAll(overrideBindings);

    renderJitBindings(res, moduleBindings, config, extensions);
    renderBindingChains(res, moduleBindings);
    return res.toString();
}
 
Example #8
Source File: ModulesSupport.java    From dropwizard-guicey with MIT License 5 votes vote down vote up
/**
 * Search for extensions in guice bindings (directly declared in modules).
 * Only user provided modules are analyzed. Overriding modules are not analyzed.
 * <p>
 * Use guice SPI. In order to avoid duplicate analysis in injector creation time, wrap
 * parsed elements as new module (and use it instead of original modules). Also, if
 * bound extension is disabled, target binding is simply removed (in order to
 * provide the same disable semantic as with usual extensions).
 *
 * @param context configuration context
 * @return list of repackaged modules to use
 */
private static List<Module> analyzeModules(final ConfigurationContext context,
                                           final Stopwatch modulesTimer) {
    List<Module> modules = context.getNormalModules();
    final Boolean configureFromGuice = context.option(AnalyzeGuiceModules);
    // one module mean no user modules registered
    if (modules.size() > 1 && configureFromGuice) {
        // analyzing only user bindings (excluding overrides and guicey technical bindings)
        final GuiceBootstrapModule bootstrap = (GuiceBootstrapModule) modules.remove(modules.size() - 1);
        try {
            // find extensions and remove bindings if required (disabled extensions)
            final Stopwatch gtime = context.stat().timer(Stat.BindingsResolutionTime);
            final List<Element> elements = new ArrayList<>(
                    Elements.getElements(context.option(InjectorStage), modules));
            gtime.stop();

            // exclude analysis time from modules processing time (it's installer time)
            modulesTimer.stop();
            analyzeAndFilterBindings(context, modules, elements);
            modulesTimer.start();

            // wrap raw elements into module to avoid duplicate work on guice startup and put back bootstrap
            modules = Arrays.asList(Elements.getModule(elements), bootstrap);
        } catch (Exception ex) {
            // better show meaningful message then just fail entire startup with ambiguous message
            // NOTE if guice configuration is not OK it will fail here too, but user will see injector creation
            // error as last error in logs.
            LOGGER.error("Failed to analyze guice bindings - skipping this step. Note that configuration"
                    + " from bindings may be switched off with " + GuiceyOptions.class.getSimpleName() + "."
                    + AnalyzeGuiceModules.name() + " option.", ex);
            // recover and use original modules
            modules.add(bootstrap);
            if (!modulesTimer.isRunning()) {
                modulesTimer.start();
            }
        }
    }
    return modules;
}
 
Example #9
Source File: DependencyCollector.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
public DependencyCollector process(Module... modules) {
    processElements(Elements.getElements(modules));
    return this;
}
 
Example #10
Source File: DependencyCollector.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
public DependencyCollector process(Iterable<? extends Module> modules) {
    processElements(Elements.getElements(Stage.TOOL, modules));
    return this;
}
 
Example #11
Source File: ElementUtils.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
public static List<Element> visit(ElementVisitor<?> visitor, Iterable<? extends Module> modules) {
    final List<Element> elements = Elements.getElements(Stage.TOOL, modules);
    elements.forEach(e -> e.acceptVisitor(visitor));
    return elements;
}
 
Example #12
Source File: GuiceRepository.java    From vespa with Apache License 2.0 4 votes vote down vote up
public void install(Module module) {
    modules.put(module, Elements.getElements(module));
    injector = null;
}
 
Example #13
Source File: SecurityModule.java    From seed with Mozilla Public License 2.0 4 votes vote down vote up
private Module removeSecurityManager(PrivateModule module) {
    return new ModuleWithoutSecurityManager((PrivateElements) Elements.getElements(module).iterator().next());
}