Java Code Examples for javax.inject.Provider

The following are top voted examples for showing how to use javax.inject.Provider. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: ProjectAres   File: DataDogClient.java   View source code 6 votes vote down vote up
String[] renderedTags() {
    final StringBuilder sb = new StringBuilder();
    boolean some = false;
    for(Provider<Tagger> provider : taggers.get()) {
        final Tagger tagger;
        try {
            tagger = Injection.unwrappingExceptions(OutOfScopeException.class, provider);
        } catch(OutOfScopeException e) {
            // If the tagger is out of scope, just omit its tags,
            // but log a warning in case this hides an unexpected exception.
            logger.warning("Ignoring out-of-scope tagger (" + e.toString() + ")");
            continue;
        }

        final ImmutableSet<Tag> tags = tagger.tags();
        if(!tags.isEmpty()) {
            if(some) sb.append(',');
            some = true;
            sb.append(tagSetCache.getUnchecked(tags));
        }
    }
    return some ? new String[] {sb.toString()} : EMPTY;
}
 
Example 2
Project: minijax   File: InjectorTest.java   View source code 6 votes vote down vote up
@Test
public void testSingleton() {
    final Provider<MySingleton> provider = injector.getProvider(MySingleton.class);
    assertNotNull(provider);

    final MySingleton instance = provider.get();
    assertNotNull(instance);

    final Provider<MySingleton> provider2 = injector.getProvider(MySingleton.class);
    assertNotNull(provider2);
    assertEquals(provider, provider2);

    final MySingleton instance2 = provider2.get();
    assertNotNull(instance2);
    assertEquals(instance, instance2);
    assertTrue(instance == instance2);
}
 
Example 3
Project: GmArchMvvm   File: ViewModelFactory.java   View source code 6 votes vote down vote up
@NonNull
@SuppressWarnings("unchecked")
@Override
public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
    Provider<? extends ViewModel> creator = creators.get(modelClass);
    if (creator == null) {
        for (Map.Entry<Class<? extends ViewModel>, Provider<ViewModel>> entry : creators.entrySet()) {
            if (modelClass.isAssignableFrom(entry.getKey())) {
                creator = entry.getValue();
                break;
            }
        }
    }
    if (creator == null) {
        throw new IllegalArgumentException("unknown model class " + modelClass);
    }
    try {
        return (T) creator.get();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 4
Project: truevfs   File: TArchiveDetector.java   View source code 6 votes vote down vote up
/**
 * Constructs a new {@code TArchiveDetector} by filtering the given driver
 * provider for all canonicalized extensions in the {@code extensions} list.
 *
 * @param  provider the file system driver provider to filter.
 * @param  extensions A list of file name extensions which shall identify
 *         prospective archive files.
 *         If this is {@code null}, no filtering is applied and all drivers
 *         known by the given provider are available for use with this
 *         archive detector.
 * @throws IllegalArgumentException If any of the extensions in the list
 *         names a extension for which no file system driver is known by the
 *         provider.
 * @see    ExtensionSet Syntax constraints for extension lists.
 */
public TArchiveDetector(final Provider<Map<FsScheme, FsDriver>> provider,
                        final @CheckForNull String extensions) {
    final ExtensionSet available = extensions(provider);
    ExtensionSet accepted;
    if (null == extensions) {
        accepted = available;
    } else {
        accepted = new ExtensionSet(extensions);
        if (accepted.retainAll(available)) {
            accepted = new ExtensionSet(extensions);
            accepted.removeAll(available);
            assert !accepted.isEmpty();
            throw new IllegalArgumentException(
                    "\"" + accepted + "\" (no archive driver installed for these extensions)");
        }
    }
    this.extensions = accepted;
    this.drivers = provider.get();
}
 
Example 5
Project: Lagerta   File: Commander.java   View source code 6 votes vote down vote up
@Inject
public Commander(
    Ignite ignite,
    RPCManager manager,
    @Named(DataCapturerBusConfiguration.CLUSTER_ID) UUID clusterId,
    @Named(DataCapturerBusConfiguration.RPC_ADDRESS) String address,
    @Named(DataCapturerBusConfiguration.SUPER_CLUSTER_ADDRESS) String superClusterAddress,
    DataRecoveryConfig dataRecoveryConfig,
    Provider<ActiveCacheStoreService> mainInterfaceProvider,
    PublisherReplicaService replicaService
) {
    this.ignite = ignite;
    this.manager = manager;
    this.clusterId = clusterId;
    this.address = address;
    this.superClusterAddress = superClusterAddress;
    this.dataRecoveryConfig = dataRecoveryConfig;
    this.mainInterfaceProvider = mainInterfaceProvider;
    this.replicaService = replicaService;
}
 
Example 6
Project: dremio-oss   File: TestTokenManager.java   View source code 6 votes vote down vote up
@BeforeClass
public static void startServices() throws Exception {
  provider = new LocalKVStoreProvider(DremioTest.CLASSPATH_SCAN_RESULT, null, true, false);
  provider.start();
  manager = new TokenManagerImpl(
      new Provider<KVStoreProvider>() {
        @Override
        public KVStoreProvider get() {
          return provider;
        }
      },
      new Provider<SchedulerService>() {
        @Override
        public SchedulerService get() {
          return mock(SchedulerService.class);
        }
      },
      false, 10, 10);
  manager.start();
}
 
Example 7
Project: android-architecture-boilerplate   File: ViewModelFactory.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T extends ViewModel> T create(Class<T> modelClass) {
    Provider<? extends ViewModel> creator = mCreators.get(modelClass);
    if (creator == null) {
        for (Map.Entry<Class<? extends ViewModel>, Provider<ViewModel>> entry : mCreators
                .entrySet()) {
            if (modelClass.isAssignableFrom(entry.getKey())) {
                creator = entry.getValue();
                break;
            }
        }
    }
    if (creator == null) {
        throw new IllegalArgumentException("unknown model class " + modelClass);
    }
    try {
        return (T) creator.get();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 8
Project: minijax   File: InjectorTest.java   View source code 6 votes vote down vote up
@Test
public void testProviderFieldInjection() {
    final Provider<ProviderFieldInjection> providerInjectionProvider = injector.getProvider(ProviderFieldInjection.class);
    assertNotNull(providerInjectionProvider);

    final ProviderFieldInjection providerInjection = providerInjectionProvider.get();
    assertNotNull(providerInjection);
    assertNotNull(providerInjection.provider);

    final C instance1 = providerInjection.provider.get();
    assertNotNull(instance1);

    final C instance2 = providerInjection.provider.get();
    assertNotNull(instance2);
    assertNotEquals(instance1, instance2);
}
 
Example 9
Project: minijax   File: InjectorTest.java   View source code 6 votes vote down vote up
@Test
public void testSimple() {
    final Provider<C> provider = injector.getProvider(C.class);
    assertNotNull(provider);

    final C instance = provider.get();
    assertNotNull(instance);

    final Provider<C> provider2 = injector.getProvider(C.class);
    assertNotNull(provider2);
    assertEquals(provider, provider2);

    final C instance2 = provider2.get();
    assertNotNull(instance2);
    assertNotEquals(instance, instance2);
}
 
Example 10
Project: RNLearn_Project1   File: ModuleHolder.java   View source code 6 votes vote down vote up
public ModuleHolder(
  String name,
  boolean canOverrideExistingModule,
  boolean supportsWebWorkers,
  boolean needsEagerInit,
  boolean hasConstants,
  Provider<? extends NativeModule> provider) {
  mName = name;
  mCanOverrideExistingModule = canOverrideExistingModule;
  mSupportsWebWorkers = supportsWebWorkers;
  mHasConstants = hasConstants;
  mProvider = provider;
  if (needsEagerInit) {
    mModule = create();
  }
}
 
Example 11
Project: dremio-oss   File: PDFSService.java   View source code 6 votes vote down vote up
public PDFSService(
    final Provider<SabotContext> contextProvider,
    Provider<FabricService> fabricService,
    SabotConfig config,
    BufferAllocator allocator,
    PDFSMode mode) {
  final Provider<Iterable<NodeEndpoint>> nodeProvider = new Provider<Iterable<NodeEndpoint>>(){
    @Override
    public Iterable<NodeEndpoint> get() {
      return contextProvider.get().getExecutors();
    }};

  Provider<NodeEndpoint> identityProvider = new Provider<NodeEndpoint>(){
    @Override
    public NodeEndpoint get() {
      return contextProvider.get().getEndpoint();
    }};
  this.fabricService = fabricService;

  this.identityProvider = identityProvider;
  this.nodeProvider = nodeProvider;
  this.config = config;
  this.allocator = allocator.newChildAllocator("pdfs-allocator", 0, Long.MAX_VALUE);
  this.allowLocalAccess = mode == PDFSMode.DATA;
}
 
Example 12
Project: dremio-oss   File: Upgrade.java   View source code 5 votes vote down vote up
public static UpgradeStats upgrade(final SabotConfig sabotConfig, final ScanResult classpathScan,
    final KVStoreProvider storeProvider) throws Exception {
  final KVStore<String, ClusterIdentity> supportStore = storeProvider.getStore(SupportStoreCreator.class);
  final ClusterIdentity identity = Preconditions.checkNotNull(supportStore.get(SupportService.CLUSTER_ID), "No Cluster Identity found");

  final Version kvStoreVersion = retrieveStoreVersion(identity);
  System.out.println("KVStore version is " + kvStoreVersion.getVersion());
  ensureUpgradeSupported(kvStoreVersion);


  final LogicalPlanPersistence lpPersistence = new LogicalPlanPersistence(sabotConfig, classpathScan);
  final UpgradeContext context = new UpgradeContext(new Provider<KVStoreProvider>() {
    @Override
    public KVStoreProvider get() {
      return storeProvider;
    }
  }, lpPersistence);
  for (UpgradeTask task : TASKS) {
    if (kvStoreVersion.compareTo(task.getMaxVersion()) < 0) {
      System.out.println(task);
      task.upgrade(context);
    } else {
      System.out.println("Skipping " + task);
    }
    // let exceptions propagate to main()
  }

  updateStoreVersion(supportStore, identity);

  return context.getUpgradeStats();
}
 
Example 13
Project: testee.fi   File: SingletonHolder.java   View source code 5 votes vote down vote up
public SingletonHolder(
        final Class<T> beanClass,
        final Provider<Pair<T, Collection<ResourceReference<?>>>> factory,
        final InterceptorChain chain
) {
    this.beanClass = beanClass;
    this.factory = factory;
    proxyInstance = createProxy(beanClass, chain);
}
 
Example 14
Project: Mastering-Java-EE-Development-with-WildFly   File: Car.java   View source code 5 votes vote down vote up
@Inject
public Car(Provider<Seat> seatProvider) {
	Seat driver = seatProvider.get();
	logger.info(driver + "");
	Seat passenger = seatProvider.get();
	logger.info(passenger + "");
}
 
Example 15
Project: act-beetlsql   File: BeetlSqlService.java   View source code 5 votes vote down vote up
public void prepareMapperClass(Class<? extends BaseMapper> mapperClass, Class<?> modelClass) {
    Object o = Proxy.newProxyInstance(mapperClass.getClassLoader(),
            new Class<?>[]{mapperClass},
            new MapperJavaProxy(new DefaultMapperBuilder(beetlSql), beetlSql, mapperClass));
    final BaseMapper mapper = $.cast(o);
    mapperMap.put(mapperClass, mapper);
    mapperMap.put(modelClass, mapper);
    Genie genie = Act.getInstance(Genie.class);
    genie.registerProvider(mapperClass, new Provider() {
        @Override
        public Object get() {
            return mapper;
        }
    });
}
 
Example 16
Project: verify-hub   File: SamlEngineIntegrationApplication.java   View source code 5 votes vote down vote up
@Override
protected Module bindInfinispan(Provider<InfinispanCacheManager> ignored) {
    return new AbstractModule() {
        @Override
        protected void configure() {
            bind(InfinispanCacheManager.class).toProvider((javax.inject.Provider<InfinispanCacheManager>) () -> new InfinispanCacheManager(mock(MetricRegistry.class, RETURNS_MOCKS), TestCacheManagerFactory.createCacheManager()));
        }
    };
}
 
Example 17
Project: dremio-oss   File: PDFSService.java   View source code 5 votes vote down vote up
public PDFSService(
    Provider<FabricService> fabricService,
    Provider<NodeEndpoint> identityProvider,
    Provider<Iterable<NodeEndpoint>> nodeProvider,
    SabotConfig config,
    BufferAllocator allocator,
    PDFSMode mode) {
  this.fabricService = fabricService;
  this.identityProvider = identityProvider;
  this.nodeProvider = nodeProvider;
  this.config = config;
  this.allocator = allocator.newChildAllocator("pdfs-allocator", 0, Long.MAX_VALUE);
  this.allowLocalAccess = mode == PDFSMode.DATA;
}
 
Example 18
Project: ProjectAres   File: InjectionStore.java   View source code 5 votes vote down vote up
public <T> T provide(Key<T> key, Provider<T> provider) {
    T t = (T) map.get(key);
    if(t != null) return t;

    t = provider.get();
    if(!Scopes.isCircularProxy(t)) {
        store(key, t);
    }

    return t;
}
 
Example 19
Project: businessworks   File: ProviderInternalFactory.java   View source code 5 votes vote down vote up
protected T circularGet(final Provider<? extends T> provider, final Errors errors,
    InternalContext context, final Dependency<?> dependency,
    ProvisionListenerStackCallback<T> provisionCallback)
    throws ErrorsException {    
  final ConstructionContext<T> constructionContext = context.getConstructionContext(this);

  // We have a circular reference between constructors. Return a proxy.
  if (constructionContext.isConstructing()) {
      Class<?> expectedType = dependency.getKey().getTypeLiteral().getRawType();
      // TODO: if we can't proxy this object, can we proxy the other object?
      @SuppressWarnings("unchecked")
      T proxyType = (T) constructionContext.createProxy(
          errors, context.getInjectorOptions(), expectedType);
      return proxyType;
  }

  // Optimization: Don't go through the callback stack if no one's listening.
  constructionContext.startConstruction();
  try {
    if (!provisionCallback.hasListeners()) {
      return provision(provider, errors, dependency, constructionContext);
    } else {
      return provisionCallback.provision(errors, context, new ProvisionCallback<T>() {
        public T call() throws ErrorsException {
          return provision(provider, errors, dependency, constructionContext);
        }
      });
    }
  } finally {
    constructionContext.removeCurrentReference();
    constructionContext.finishConstruction();
  }
}
 
Example 20
Project: minijax   File: MinijaxInjector.java   View source code 5 votes vote down vote up
@SuppressWarnings({ "squid:S3824", "unchecked" })
<T> Provider<T> getProvider(final Key<T> key, final Set<Key<?>> chain) {
    Provider<T> result = (Provider<T>) providers.get(key);

    if (result == null) {
        result = buildProvider(key, chain);
        providers.put(key, result);
    }

    return result;
}
 
Example 21
Project: queries   File: QueriesGuiceSupport.java   View source code 5 votes vote down vote up
public static Module queriesModule(Function<QueriesSources, Queries> queriesSupplier) {
	return new AbstractModule() {
		@Override
		protected void configure() {

			com.google.inject.Provider<SourcesCollector> provider = binder().getProvider(SourcesCollector.class);

			bind(Queries.class).toProvider(() -> queriesSupplier.apply(provider.get().getSources()))
					.in(Singleton.class);
		}
	};
}
 
Example 22
Project: ProjectAres   File: Injection.java   View source code 5 votes vote down vote up
/**
 * Return the type that is depended on by injecting the given type.
 * These types are the same, unless the injected type is a {@link Provider},
 * in which case the dependency is on the provided type.
 */
public static TypeLiteral<?> dependencyType(TypeLiteral<?> injectedType) {
    if(isImplicitProvider(injectedType)) {
        return providedType((TypeLiteral<? extends Provider<Object>>) injectedType);
    } else {
        return injectedType;
    }
}
 
Example 23
Project: minijax   File: MinijaxInjector.java   View source code 5 votes vote down vote up
private <T> Provider<T> buildProvider(final Key<T> key, final Set<Key<?>> chain) {
    final Provider<T> p;

    switch (key.getStrategy()) {
    case CONTEXT:
        p = new ContextProvider<>(key);
        break;
    case COOKIE:
        p = new CookieParamProvider<>(key);
        break;
    case FORM:
        p = new FormParamProvider<>(key);
        break;
    case HEADER:
        p = new HeaderParamProvider<>(key);
        break;
    case PATH:
        p = new PathParamProvider<>(key);
        break;
    case QUERY:
        p = new QueryParamProvider<>(key);
        break;
    default:
        p = new ConstructorProviderBuilder<>(this, key, chain).buildConstructorProvider();
        break;
    }

    if (key.getType().getAnnotation(Singleton.class) != null) {
        return new SingletonProvider<>(p);
    } else if (key.getType().getAnnotation(RequestScoped.class) != null) {
        return new RequestScopedProvider<>(key, p);
    } else {
        return p;
    }
}
 
Example 24
Project: dremio-oss   File: AccelerationListManagerImpl.java   View source code 5 votes vote down vote up
@Override
public void start() throws Exception {
  accelerationStore.start();
  materializationStore.start();

  this.namespaceService = new Provider<NamespaceService>() {
    @Override
    public NamespaceService get() {
      return contextProvider.get().getNamespaceService(SYSTEM_USERNAME);
    }
  };
}
 
Example 25
Project: minijax   File: ConstructorProvider.java   View source code 5 votes vote down vote up
public ConstructorProvider(
        final Constructor<T> ctor,
        final Provider<?>[] paramProviders,
        final List<InjectionSet<? super T>> injectionSets) {

    this.ctor = ctor;
    this.paramProviders = paramProviders;
    this.injectionSets = injectionSets;
}
 
Example 26
Project: curiostack   File: EggworldService.java   View source code 5 votes vote down vote up
@Inject
EggworldService(
    Provider<CheckIngredientsGraph.Component.Builder> checkIngredientsGraph,
    Provider<FindRecipeGraph.Component.Builder> findRecipeGraph) {
  this.checkIngredientsGraph = checkIngredientsGraph;
  this.findRecipeGraph = findRecipeGraph;
}
 
Example 27
Project: dremio-oss   File: MasterStatusListener.java   View source code 5 votes vote down vote up
public MasterStatusListener(Provider<ClusterCoordinator> clusterCoordinator,
                            String masterNode, int masterPort, boolean isMaster) {
  this.clusterCoordinator = clusterCoordinator;
  this.masterNode = masterNode;
  this.masterUp = isMaster;
  this.masterPort = masterPort;
}
 
Example 28
Project: Graywater   File: HeaderBinder.java   View source code 5 votes vote down vote up
@Override
public void prepare(@NonNull final Primitive.Header model,
                    final List<Provider<GraywaterAdapter.Binder<
		                    ? super Primitive.Header, PrimitiveViewHolder, ? extends PrimitiveViewHolder>>> binderList,
                    final int binderIndex) {

}
 
Example 29
Project: dremio-oss   File: LocalKVStoreProvider.java   View source code 5 votes vote down vote up
public LocalKVStoreProvider(ScanResult scan, Provider<FabricService> fabricService, BufferAllocator allocator, String hostName,
                            String baseDirectory, boolean inMemory, boolean timed, boolean validateOCC, boolean disableOCC) {
  coreStoreProvider = new CoreStoreProviderImpl(baseDirectory, inMemory, timed, validateOCC, disableOCC);
  this.fabricService = fabricService;
  this.allocator = allocator;
  this.hostName = hostName;
  this.scan = scan;
}
 
Example 30
Project: Graywater   File: ColorNameToastBinder.java   View source code 5 votes vote down vote up
@Override
public void prepare(@NonNull final ColorNamePrimitive model,
                    final List<Provider<GraywaterAdapter.Binder<
		                    ? super ColorNamePrimitive, PrimitiveViewHolder, ? extends PrimitiveViewHolder>>> binderList,
                    final int binderIndex) {

}
 
Example 31
Project: dremio-oss   File: PDFSConfig.java   View source code 5 votes vote down vote up
public PDFSConfig(ExecutorService executor, FabricRunnerFactory runnerFactory, BufferAllocator allocator,
    Provider<Iterable<NodeEndpoint>> endpointProvider, NodeEndpoint localIdentity, boolean localAccessAllowed) {
  super();
  this.executor = executor;
  this.runnerFactory = runnerFactory;
  this.allocator = allocator;
  this.endpointProvider = endpointProvider;
  this.localIdentity = localIdentity;
  this.localAccessAllowed = localAccessAllowed;
}
 
Example 32
Project: Graywater   File: PaletteItemBinder.java   View source code 5 votes vote down vote up
@Override
public void act(@NonNull final Palette model,
                @NonNull final PrimitiveViewHolder holder,
                @NonNull final View v,
                @NonNull final List<Provider<GraywaterAdapter.Binder<
		                ? super Palette, PrimitiveViewHolder, ? extends PrimitiveViewHolder>>> binderList,
                final int binderIndex,
                @Nullable final Object obj) {

}
 
Example 33
Project: Graywater   File: HeaderPrimitiveItemBinder.java   View source code 5 votes vote down vote up
@NonNull
@Override
public List<Provider<
		? extends GraywaterAdapter.Binder<Primitive.Header, PrimitiveViewHolder, ? extends PrimitiveViewHolder>>>
getBinderList(@NonNull final Primitive.Header model, final int position) {
	return new ArrayList<Provider<
			? extends GraywaterAdapter.Binder<Primitive.Header, PrimitiveViewHolder, ? extends PrimitiveViewHolder>>>() {{
		add(mHeaderBinder);
	}};
}
 
Example 34
Project: joal   File: JoalConfigProviderTest.java   View source code 5 votes vote down vote up
@Test
public void shouldFailToGetConfIfNotInitialized() throws FileNotFoundException {
    final Provider<AppConfiguration> provider = new JoalConfigProvider(new ObjectMapper(), resourcePath.toString(), Mockito.mock(ApplicationEventPublisher.class));

    assertThatThrownBy(provider::get)
            .isInstanceOf(IllegalStateException.class)
            .hasMessage("Attempted to get configuration before init.");
}
 
Example 35
Project: Graywater   File: ColorNamePrimitiveItemBinder.java   View source code 5 votes vote down vote up
@Override
public void act(@NonNull final ColorNamePrimitive model,
                @NonNull final PrimitiveViewHolder holder,
                @NonNull final View v,
                @NonNull final List<Provider<GraywaterAdapter.Binder<
		                ? super ColorNamePrimitive, PrimitiveViewHolder, ? extends PrimitiveViewHolder>>> binderList,
                final int binderIndex,
                @Nullable final Object obj) {
	Toast.makeText(v.getContext(), model.getString(), Toast.LENGTH_SHORT).show();

	final PrimitiveAdapter adapter = mAdapter.get();

	adapter.add(adapter.getItemPosition(holder.getAdapterPosition()) + 1,
			new ColorNamePrimitive(model.getColor(), model.getString() + "+"), true);
}
 
Example 36
Project: ProjectAres   File: DataDogClient.java   View source code 5 votes vote down vote up
@Inject DataDogClient(Loggers loggers, DataDogConfig config, Provider<StatsDClient> clientProvider, Provider<Collection<Provider<Tagger>>> taggers) {
    this.logger = loggers.get(getClass());
    this.config = config;
    this.clientProvider = clientProvider;
    this.taggers = taggers;

    this.client = clientProvider.get();
}
 
Example 37
Project: Graywater   File: GraywaterAdapter.java   View source code 5 votes vote down vote up
/**
 * @param model
 * 		the model to get parts for.
 * @param position
 * 		the position of the model.
 * @return the list of binders to use.
 */
@Nullable
protected List<Provider<Binder<? super T, VH, ? extends VH>>> getParts(final T model, final int position) {
	final List<Provider<Binder<? super T, VH, ? extends VH>>> list;

	final ItemBinder itemBinder = getItemBinder(model);

	if (itemBinder != null) {
		list = itemBinder.getBinderList(model, position);
	} else {
		list = null;
	}

	return list;
}
 
Example 38
Project: Graywater   File: GraywaterAdapter.java   View source code 5 votes vote down vote up
/**
 * Computes the position of the item and the position of the binder within the item's binder list.
 * Note that this is an <i>O(n)</i> operation.
 *
 * @param viewHolderPosition
 * 		the position of the view holder in the adapter.
 * @return the item position and the position of the binder in the item's binder list.
 */
@VisibleForTesting
BinderResult computeItemAndBinderIndex(final int viewHolderPosition) {
	// subtract off the length of each list until we get to the desired item

	final int itemIndex = mViewHolderToItemPositionCache.get(viewHolderPosition);
	final T item = mItems.get(itemIndex);
	final List<Provider<Binder<? super T, VH, ? extends VH>>> binders = mBinderListCache.get(itemIndex);
	// index of the first item in the set of viewholders for the current item.
	final int firstVHPosForItem = mItemPositionToFirstViewHolderPositionCache.get(itemIndex);

	return new BinderResult(item, itemIndex, binders, viewHolderPosition - firstVHPosForItem);
}
 
Example 39
Project: dremio-oss   File: RemoteKVStoreProvider.java   View source code 5 votes vote down vote up
public RemoteKVStoreProvider(ScanResult scan, Provider<FabricService> fabricService, BufferAllocator allocator, String hostName, String masterHostName, int masterPort) {
  this.fabricService = fabricService;
  this.allocator = allocator;
  this.hostName = hostName;
  this.masterHostName = masterHostName;
  this.masterPort = masterPort;
  this.scan = scan;
}
 
Example 40
Project: Graywater   File: GraywaterAdapter.java   View source code 5 votes vote down vote up
/**
 * Note that this is an <i>O(n)</i> operation, since the cache needs to be updated.
 *
 * @param position
 * 		the position to insert into the list.
 * @param item
 * 		the item to add. Note that if it is <code>null</code>, there is no way to determine which binder to use.
 * @param notify
 * 		whether or not to notify the adapter.
 */
public void add(final int position, @NonNull final T item, final boolean notify) {
	final int numViewHolders = getViewHolderCount(position);

	final List<Provider<Binder<? super T, VH, ? extends VH>>> binders = getParts(item, position);

	mItems.add(position, item);
	mBinderListCache.add(position, binders);

	if (binders != null) {
		if (notify) {
			notifyItemRangeInserted(numViewHolders, binders.size());
		}

		final List<Integer> itemPositions = new ArrayList<>();
		for (int i = 0; i < binders.size(); i++) {
			itemPositions.add(position);
		}

		mViewHolderToItemPositionCache.addAll(numViewHolders, itemPositions);
		for (int viewHolderIndex = numViewHolders + binders.size(); viewHolderIndex < mViewHolderToItemPositionCache.size();
		     viewHolderIndex++) {
			mViewHolderToItemPositionCache.set(viewHolderIndex, mViewHolderToItemPositionCache.get(viewHolderIndex) + 1);
			mViewHolderPreparedCache.remove(viewHolderIndex);
		}

		mItemPositionToFirstViewHolderPositionCache.add(position, numViewHolders);
		for (int itemIndex = position + 1; itemIndex < mItemPositionToFirstViewHolderPositionCache.size(); itemIndex++) {
			mItemPositionToFirstViewHolderPositionCache.set(itemIndex,
					mItemPositionToFirstViewHolderPositionCache.get(itemIndex) + binders.size());
		}
	}
}