org.elasticsearch.common.inject.Injector Java Examples

The following examples show how to use org.elasticsearch.common.inject.Injector. 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: Multibinder.java    From crate with Apache License 2.0 6 votes vote down vote up
/**
 * Invoked by Guice at Injector-creation time to prepare providers for each
 * element in this set. At this time the set's size is known, but its
 * contents are only evaluated when get() is invoked.
 */
@Inject
public void initialize(Injector injector) {
    providers = new ArrayList<>();
    Set<Dependency<?>> dependencies = new HashSet<>();
    for (Binding<?> entry : injector.findBindingsByType(elementType)) {
        if (keyMatches(entry.getKey())) {
            @SuppressWarnings("unchecked") // protected by findBindingsByType()
                    Binding<T> binding = (Binding<T>) entry;
            providers.add(binding.getProvider());
            dependencies.add(Dependency.get(binding.getKey()));
        }
    }

    this.dependencies = unmodifiableSet(dependencies);
    this.binder = null;
}
 
Example #2
Source File: FactoryProvider2.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
/**
 * At injector-creation time, we initialize the invocation handler. At this time we make sure
 * all factory methods will be able to build the target types.
 */
@Inject
public void initialize(Injector injector) {
    if (this.injector != null) {
        throw new ConfigurationException(Collections.singletonList(new Message(FactoryProvider2.class,
            "Factories.create() factories may only be used in one Injector!")));
    }

    this.injector = injector;

    for (Method method : returnTypesByMethod.keySet()) {
        Object[] args = new Object[method.getParameterTypes().length];
        Arrays.fill(args, "dummy object for validating Factories");
        getBindingFromNewInjector(method, args); // throws if the binding isn't properly configured
    }
}
 
Example #3
Source File: Multibinder.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
/**
 * Invoked by Guice at Injector-creation time to prepare providers for each
 * element in this set. At this time the set's size is known, but its
 * contents are only evaluated when get() is invoked.
 */
@Inject
public void initialize(Injector injector) {
    providers = new ArrayList<>();
    List<Dependency<?>> dependencies = new ArrayList<>();
    for (Binding<?> entry : injector.findBindingsByType(elementType)) {

        if (keyMatches(entry.getKey())) {
            @SuppressWarnings("unchecked") // protected by findBindingsByType()
                    Binding<T> binding = (Binding<T>) entry;
            providers.add(binding.getProvider());
            dependencies.add(Dependency.get(binding.getKey()));
        }
    }

    this.dependencies = ImmutableSet.copyOf(dependencies);
    this.binder = null;
}
 
Example #4
Source File: IkESPluginTest.java    From es-ik with Apache License 2.0 6 votes vote down vote up
@Test
public void testDefaultsIcuAnalysis() {
    Index index = new Index("test");

    Settings settings = ImmutableSettings.settingsBuilder()
            .put("path.home", "none")
            .put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT)
            .build();

    Injector parentInjector = new ModulesBuilder().add(new SettingsModule(ImmutableSettings.EMPTY), new EnvironmentModule(new Environment(settings)), new IndicesAnalysisModule()).createInjector();
    Injector injector = new ModulesBuilder().add(
            new IndexSettingsModule(index, settings),
            new IndexNameModule(index),
            new AnalysisModule(ImmutableSettings.EMPTY, parentInjector.getInstance(IndicesAnalysisService.class)).addProcessor(new IKAnalysisBinderProcessor()))
            .createChildInjector(parentInjector);

    AnalysisService analysisService = injector.getInstance(AnalysisService.class);

    TokenizerFactory tokenizerFactory = analysisService.tokenizer("ik_tokenizer");
    MatcherAssert.assertThat(tokenizerFactory, instanceOf(IKTokenizerFactory.class));


}
 
Example #5
Source File: HanLpAnalysisTests.java    From elasticsearch-analysis-hanlp with Apache License 2.0 6 votes vote down vote up
@Test
public void testDefaultsIcuAnalysis() {
    Index index = new Index("test");
    Settings settings = settingsBuilder()
        .put("path.home", createTempDir())
        .put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT)
        .build();
    Injector parentInjector = new ModulesBuilder().add(new SettingsModule(EMPTY_SETTINGS), new EnvironmentModule(new Environment(settings))).createInjector();
    Injector injector = new ModulesBuilder().add(
        new IndexSettingsModule(index, settings),
        new IndexNameModule(index),
        new AnalysisModule(EMPTY_SETTINGS, parentInjector.getInstance(IndicesAnalysisService.class)).addProcessor(new HanLpAnalysisBinderProcessor()))
                                            .createChildInjector(parentInjector);

    AnalysisService analysisService = injector.getInstance(AnalysisService.class);

    TokenizerFactory tokenizerFactory = analysisService.tokenizer("smartcn_tokenizer");
    MatcherAssert.assertThat(tokenizerFactory, instanceOf(HanLpTokenizerTokenizerFactory.class));
}
 
Example #6
Source File: UntargettedBindingImpl.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public UntargettedBindingImpl(Injector injector, Key<T> key, Object source) {
    super(injector, key, source, new InternalFactory<T>() {
        @Override
        public T get(Errors errors, InternalContext context, Dependency<?> dependency) {
            throw new AssertionError();
        }
    }, Scoping.UNSCOPED);
}
 
Example #7
Source File: BlobIndices.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public BlobShard blobShard(String index, int shardId) {
    IndexService indexService = indicesService.indexService(index);
    if (indexService != null) {
        try {
            Injector injector = indexService.shardInjectorSafe(shardId);
            return injector.getInstance(BlobShard.class);
        } catch (ShardNotFoundException e) {
            return null;
        }
    }
    return null;
}
 
Example #8
Source File: BindingImpl.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public BindingImpl(Injector injector, Key<T> key, Object source,
                   InternalFactory<? extends T> internalFactory, Scoping scoping) {
    this.injector = injector;
    this.key = key;
    this.source = source;
    this.internalFactory = internalFactory;
    this.scoping = scoping;
}
 
Example #9
Source File: FactoryProvider.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Inject
void setInjectorAndCheckUnboundParametersAreInjectable(Injector injector) {
    this.injector = injector;
    for (AssistedConstructor<?> c : factoryMethodToConstructor.values()) {
        for (Parameter p : c.getAllParameters()) {
            if (!p.isProvidedByFactory() && !paramCanBeInjected(p, injector)) {
                // this is lame - we're not using the proper mechanism to add an
                // error to the injector. Throughout this class we throw exceptions
                // to add errors, which isn't really the best way in Guice
                throw newConfigurationException("Parameter of type '%s' is not injectable or annotated "
                        + "with @Assisted for Constructor '%s'", p, c);
            }
        }
    }
}
 
Example #10
Source File: FactoryProvider2.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a child injector that binds the args, and returns the binding for the method's result.
 */
public Binding<?> getBindingFromNewInjector(final Method method, final Object[] args) {
    checkState(injector != null,
            "Factories.create() factories cannot be used until they're initialized by Guice.");

    final Key<?> returnType = returnTypesByMethod.get(method);

    Module assistedModule = new AbstractModule() {
        @Override
        @SuppressWarnings("unchecked") // raw keys are necessary for the args array and return value
        protected void configure() {
            Binder binder = binder().withSource(method);

            int p = 0;
            for (Key<?> paramKey : paramTypes.get(method)) {
                // Wrap in a Provider to cover null, and to prevent Guice from injecting the parameter
                binder.bind((Key) paramKey).toProvider(Providers.of(args[p++]));
            }

            if (producedType != null && !returnType.equals(producedType)) {
                binder.bind(returnType).to((Key) producedType);
            } else {
                binder.bind(returnType);
            }
        }
    };

    Injector forCreate = injector.createChildInjector(assistedModule);
    return forCreate.getBinding(returnType);
}
 
Example #11
Source File: TransportGetIndicesVersionAction.java    From siren-join with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
protected ShardIndexVersion shardOperation(GetIndicesVersionRequest request, ShardRouting shardRouting) throws IOException {
  IndexService indexService = indicesService.indexServiceSafe(shardRouting.getIndex());
  IndexShard indexShard = indexService.shardSafe(shardRouting.id());

  // Get the IndexVersionShardService associated to this shard
  Injector injector = indexService.shardInjectorSafe(shardRouting.id());
  IndexVersionShardService indexVersionService = injector.getBinding(IndexVersionShardService.class).getProvider().get();
  long version = indexVersionService.getVersion();

  return new ShardIndexVersion(indexShard.routingEntry(), version);
}
 
Example #12
Source File: TransportClient.java    From elasticsearch-helper with Apache License 2.0 5 votes vote down vote up
private TransportClient(Injector injector) {
    super(injector.getInstance(Settings.class), injector.getInstance(ThreadPool.class),
            injector.getInstance(Headers.class));
    this.injector = injector;
    this.clusterName = injector.getInstance(ClusterName.class);
    this.transportService = injector.getInstance(TransportService.class);
    this.minCompatibilityVersion = injector.getInstance(Version.class).minimumCompatibilityVersion();
    this.headers = injector.getInstance(Headers.class);
    this.pingTimeout = this.settings.getAsTime("client.transport.ping_timeout", timeValueSeconds(5)).millis();
    this.proxyActionMap = injector.getInstance(ProxyActionMap.class);
}
 
Example #13
Source File: MapperTestUtils.java    From elasticsearch-analysis-baseform with Apache License 2.0 5 votes vote down vote up
public static AnalysisService newAnalysisService(Settings indexSettings) {
    Injector parentInjector = new ModulesBuilder().add(new SettingsModule(indexSettings),
            new EnvironmentModule(new Environment(indexSettings))).createInjector();
    Index index = new Index("test");
    Injector injector = new ModulesBuilder().add(
            new IndexSettingsModule(index, indexSettings),
            new IndexNameModule(index),
            new AnalysisModule(indexSettings, parentInjector.getInstance(IndicesAnalysisService.class))).createChildInjector(parentInjector);

    return injector.getInstance(AnalysisService.class);
}
 
Example #14
Source File: MapperTestUtils.java    From elasticsearch-analysis-baseform with Apache License 2.0 5 votes vote down vote up
public static MapperService newMapperService(Settings settings, Client client) {
    Settings indexSettings = Settings.builder()
            .put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT)
            .put("path.home", System.getProperty("path.home"))
            .put("client.type", "node")
            .put(settings)
            .build();
    Index index = new Index("test");
    Injector parentInjector = new ModulesBuilder()
            .add(new SettingsModule(indexSettings),
            new EnvironmentModule(new Environment(indexSettings)))
            .createInjector();
    AnalysisModule analysisModule = new AnalysisModule(indexSettings,
            parentInjector.getInstance(IndicesAnalysisService.class));
    new AnalysisBaseformPlugin(settings).onModule(analysisModule);
    Injector injector = new ModulesBuilder().add(new IndexSettingsModule(index, indexSettings),
            new IndexNameModule(index),
            analysisModule)
            .createChildInjector(parentInjector);
    AnalysisService analysisService = injector.getInstance(AnalysisService.class);
    SimilarityLookupService similarityLookupService = new SimilarityLookupService(index, indexSettings);
    Map<String, Mapper.TypeParser> mappers = registerBuiltInMappers();
    Map<String, MetadataFieldMapper.TypeParser> metadataMappers = registerBuiltInMetadataMappers();
    MapperRegistry mapperRegistry = new MapperRegistry(mappers, metadataMappers);
    return new MapperService(new Index("test"),
            indexSettings,
            analysisService,
            similarityLookupService,
            null,
            mapperRegistry);
}
 
Example #15
Source File: Exporter.java    From elasticsearch-inout-plugin with Apache License 2.0 5 votes vote down vote up
@Inject
public Exporter(VersionFetchSubPhase versionPhase, Injector injector,
        SettingsFilter settingsFilter) {
    this.fetchSubPhases = new FetchSubPhase[]{versionPhase};
    this.injector = injector;
    this.settingsFilter = settingsFilter;
}
 
Example #16
Source File: JLineRhinoCompleterTest.java    From elasticshell with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public void init() {
    Injector injector = Guice.createInjector(new ShellModule(), new JLineModule(), new RhinoShellModule());
    Context context = Context.enter();
    context.setWrapFactory(new RhinoCustomWrapFactory());
    completer = injector.getInstance(JLineRhinoCompleter.class);
}
 
Example #17
Source File: InstanceBindingImpl.java    From crate with Apache License 2.0 5 votes vote down vote up
public InstanceBindingImpl(Injector injector, Key<T> key, Object source,
                           InternalFactory<? extends T> internalFactory, Set<InjectionPoint> injectionPoints,
                           T instance) {
    super(injector, key, source, internalFactory, Scoping.UNSCOPED);
    this.injectionPoints = injectionPoints;
    this.instance = instance;
    this.provider = Providers.of(instance);
}
 
Example #18
Source File: ProviderInstanceBindingImpl.java    From crate with Apache License 2.0 5 votes vote down vote up
public ProviderInstanceBindingImpl(Injector injector, Key<T> key,
                                   Object source, InternalFactory<? extends T> internalFactory, Scoping scoping,
                                   Provider<? extends T> providerInstance,
                                   Set<InjectionPoint> injectionPoints) {
    super(injector, key, source, internalFactory, scoping);
    this.providerInstance = providerInstance;
    this.injectionPoints = injectionPoints;
}
 
Example #19
Source File: UntargettedBindingImpl.java    From crate with Apache License 2.0 5 votes vote down vote up
public UntargettedBindingImpl(Injector injector, Key<T> key, Object source) {
    super(injector, key, source, new InternalFactory<T>() {
        @Override
        public T get(Errors errors, InternalContext context, Dependency<?> dependency) {
            throw new AssertionError();
        }
    }, Scoping.UNSCOPED);
}
 
Example #20
Source File: BindingImpl.java    From crate with Apache License 2.0 5 votes vote down vote up
public BindingImpl(Injector injector, Key<T> key, Object source,
                   InternalFactory<? extends T> internalFactory, Scoping scoping) {
    this.injector = injector;
    this.key = key;
    this.source = source;
    this.internalFactory = internalFactory;
    this.scoping = scoping;
}
 
Example #21
Source File: RepositoriesService.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Inject
public RepositoriesService(Settings settings, ClusterService clusterService, TransportService transportService, RepositoryTypesRegistry typesRegistry, Injector injector) {
    super(settings);
    this.typesRegistry = typesRegistry;
    this.injector = injector;
    this.clusterService = clusterService;
    // Doesn't make sense to maintain repositories on non-master and non-data nodes
    // Nothing happens there anyway
    if (DiscoveryNode.dataNode(settings) || DiscoveryNode.masterNode(settings)) {
        clusterService.add(this);
    }
    this.verifyAction = new VerifyNodeRepositoryAction(settings, transportService, clusterService, this);
}
 
Example #22
Source File: IndicesService.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Inject
public IndicesService(Settings settings, IndicesLifecycle indicesLifecycle, IndicesAnalysisService indicesAnalysisService, Injector injector, NodeEnvironment nodeEnv) {
    super(settings);
    this.indicesLifecycle = (InternalIndicesLifecycle) indicesLifecycle;
    this.indicesAnalysisService = indicesAnalysisService;
    this.injector = injector;
    this.pluginsService = injector.getInstance(PluginsService.class);
    this.indicesLifecycle.addListener(oldShardsStats);
    this.nodeEnv = nodeEnv;
    this.shardsClosedTimeout = settings.getAsTime(INDICES_SHARDS_CLOSED_TIMEOUT, new TimeValue(1, TimeUnit.DAYS));
}
 
Example #23
Source File: ProviderInstanceBindingImpl.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public ProviderInstanceBindingImpl(Injector injector, Key<T> key,
                                   Object source, InternalFactory<? extends T> internalFactory, Scoping scoping,
                                   Provider<? extends T> providerInstance,
                                   Set<InjectionPoint> injectionPoints) {
    super(injector, key, source, internalFactory, scoping);
    this.providerInstance = providerInstance;
    this.injectionPoints = ImmutableSet.copyOf(injectionPoints);
}
 
Example #24
Source File: MapperTestUtils.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
private static AnalysisService newAnalysisService(Settings indexSettings) {
    Injector parentInjector = new ModulesBuilder().add(new SettingsModule(indexSettings), new EnvironmentModule(new Environment(indexSettings))).createInjector();
    Index index = new Index("test");
    Injector injector = new ModulesBuilder().add(
        new IndexSettingsModule(index, indexSettings),
        new IndexNameModule(index),
        new AnalysisModule(indexSettings, parentInjector.getInstance(IndicesAnalysisService.class))).createChildInjector(parentInjector);

    return injector.getInstance(AnalysisService.class);
}
 
Example #25
Source File: BlobService.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Inject
public BlobService(Settings settings,
                   ClusterService clusterService,
                   Injector injector,
                   BlobHeadRequestHandler blobHeadRequestHandler,
                   BlobEnvironment blobEnvironment) {
    super(settings);
    this.clusterService = clusterService;
    this.injector = injector;
    this.blobHeadRequestHandler = blobHeadRequestHandler;
    this.blobEnvironment = blobEnvironment;
}
 
Example #26
Source File: InstanceBindingImpl.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public InstanceBindingImpl(Injector injector, Key<T> key, Object source,
                           InternalFactory<? extends T> internalFactory, Set<InjectionPoint> injectionPoints,
                           T instance) {
    super(injector, key, source, internalFactory, Scoping.UNSCOPED);
    this.injectionPoints = ImmutableSet.copyOf(injectionPoints);
    this.instance = instance;
    this.provider = Providers.of(instance);
}
 
Example #27
Source File: PrivateElementsImpl.java    From crate with Apache License 2.0 4 votes vote down vote up
public void initInjector(Injector injector) {
    if (this.injector != null) {
        throw new IllegalStateException("injector already initialized");
    }
    this.injector = Objects.requireNonNull(injector, "injector");
}
 
Example #28
Source File: LinkedProviderBindingImpl.java    From crate with Apache License 2.0 4 votes vote down vote up
public LinkedProviderBindingImpl(Injector injector, Key<T> key, Object source,
                                 InternalFactory<? extends T> internalFactory, Scoping scoping,
                                 Key<? extends Provider<? extends T>> providerKey) {
    super(injector, key, source, internalFactory, scoping);
    this.providerKey = providerKey;
}
 
Example #29
Source File: IndicesService.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
public Injector getInjector() {
    return injector;
}
 
Example #30
Source File: ExposedBindingImpl.java    From crate with Apache License 2.0 4 votes vote down vote up
public ExposedBindingImpl(Injector injector, Object source, Key<T> key,
                          InternalFactory<T> factory, PrivateElements privateElements) {
    super(injector, key, source, factory, Scoping.UNSCOPED);
    this.privateElements = privateElements;
}