下面列出了com.google.inject.spi.DefaultElementVisitor#com.google.inject.spi.Elements 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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);
}
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);
}
}
}
@Before
public void setUp() throws Exception {
module = new EndpointsModule() {
@Override
protected void configureServlets() {
super.configureServlets();
configureEndpoints(URL_PATTERN, INIT_PARAMETERS, true);
}
};
Elements.getElements(module);
}
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);
}
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();
}
@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();
}
@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();
}
/**
* 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;
}
public DependencyCollector process(Module... modules) {
processElements(Elements.getElements(modules));
return this;
}
public DependencyCollector process(Iterable<? extends Module> modules) {
processElements(Elements.getElements(Stage.TOOL, modules));
return this;
}
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;
}
public void install(Module module) {
modules.put(module, Elements.getElements(module));
injector = null;
}
private Module removeSecurityManager(PrivateModule module) {
return new ModuleWithoutSecurityManager((PrivateElements) Elements.getElements(module).iterator().next());
}