Line data Source code
1 : // Copyright (C) 2012 The Android Open Source Project 2 : // 3 : // Licensed under the Apache License, Version 2.0 (the "License"); 4 : // you may not use this file except in compliance with the License. 5 : // You may obtain a copy of the License at 6 : // 7 : // http://www.apache.org/licenses/LICENSE-2.0 8 : // 9 : // Unless required by applicable law or agreed to in writing, software 10 : // distributed under the License is distributed on an "AS IS" BASIS, 11 : // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 : // See the License for the specific language governing permissions and 13 : // limitations under the License. 14 : 15 : package com.google.gerrit.extensions.registration; 16 : 17 : import com.google.gerrit.common.Nullable; 18 : import com.google.inject.Binding; 19 : import com.google.inject.Inject; 20 : import com.google.inject.Injector; 21 : import com.google.inject.Key; 22 : import com.google.inject.Provider; 23 : import com.google.inject.ProvisionException; 24 : import com.google.inject.TypeLiteral; 25 : import java.util.List; 26 : 27 : class DynamicItemProvider<T> implements Provider<DynamicItem<T>> { 28 : private final TypeLiteral<T> type; 29 : private final Key<DynamicItem<T>> key; 30 : 31 : @Inject private Injector injector; 32 : 33 152 : DynamicItemProvider(TypeLiteral<T> type, Key<DynamicItem<T>> key) { 34 152 : this.type = type; 35 152 : this.key = key; 36 152 : } 37 : 38 : @Override 39 : public DynamicItem<T> get() { 40 151 : return new DynamicItem<>(key, find(injector, type), PluginName.GERRIT); 41 : } 42 : 43 : @Nullable 44 : private static <T> Provider<T> find(Injector src, TypeLiteral<T> type) { 45 151 : List<Binding<T>> bindings = src.findBindingsByType(type); 46 151 : if (bindings != null && bindings.size() == 1) { 47 151 : return bindings.get(0).getProvider(); 48 150 : } else if (bindings != null && bindings.size() > 1) { 49 0 : throw new ProvisionException( 50 0 : String.format( 51 : "Multiple providers bound for DynamicItem<%s>\n" 52 : + "This is not allowed; check the server configuration.", 53 : type)); 54 : } else { 55 150 : return null; 56 : } 57 : } 58 : }